上传和下载功能

System.out.println(this.getServletContext().getContextPath());   //服务器中的只能是web应用
System.out.println(this.getServletContext().getRealPath("/WEB-INF/upload"));  //服务器中的
System.out.println(request.getServletPath()+"/WEB-INF/upload");      //浏览器中的

 

/heima_day15

 

E:\apache-tomcat-7.0.0\webapps\heima_day15\WEB-INF\upload

 

/test/WEB-INF/upload

 

1.response.setHeader("Content-disposition", "attachment;filename="+URLEncoder.encode(中文的名字,"utf-8"));         //这个如果是要中文的文件名字的话就要加URLEncoder.encode。。

URLEncoder.encode(String)是对url中的中文参数经行编码的,可以解决乱码的问题。


2.response.setContentType(this.getServletContext().getMimeType(fSource.getRealname()));  //文件的类型
InputStream in=new FileInputStream(new File(this.getServletContext().getRealPath(fSource.getSavepath()),fSource.getUuidname()));
OutputStream out=response.getOutputStream(); 
IOUtils.in2out(in, out);
IOUtils.close(in, out);

 

 

 

 

上传:

//1. 拿到DiskFileItemFactory 
           DiskFileItemFactory dItem=new DiskFileItemFactory();
           dItem.setSizeThreshold(1024*1024*2);
           dItem.setRepository(new File(this.getServletContext().getRealPath("/WEB-INF/upload")));

         

       //2.
           ServletFileUpload sUpload=
new ServletFileUpload(dItem);
           sUpload.setFileSizeMax(1024*1024*100);
           sUpload.setSizeMax(1024*1024*500);
           sUpload.setHeaderEncoding("utf-8");

 

    //3
        List<FileItem> list=  sUpload.parseRequest(request);
          for(FileItem fItem:list){
         if(fItem.isFormField()){           // 普通字段

         String name=fItem.getFieldName();
         String value=fItem.getString("utf-8");
         map.put(name, value);
         }else {
        String realname= fItem.getName();
        realname= realname.substring(realname.lastIndexOf("\\")+1);
        map.put("realname", realname);
         
        String name= UUID.randomUUID().toString()+"_"+realname;
         
        map.put("uuidname", name);
       
        InputStream in= fItem.getInputStream();   //拿到上传文件的流
             
         
        String code=Integer.toHexString( name.hashCode());
        String path=this.getServletContext().getRealPath("/WEB-INF/upload");
        char[] chs=code.toCharArray(); 
       
        String savepath="/WEB-INF/upload";
       
        for(char s:chs){
        path+="/"+s;


        savepath+="/"+s;
       
        }
       
        new File(path).mkdirs();
        map.put("savepath", savepath);
       
        FileOutputStream fout=new FileOutputStream(new File(path,name));
        IOUtils.in2out(in, fout);
        IOUtils.close(in, fout);
         
        fItem.delete();    // 删除临时文件

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值