servlet_response下载文件

  通过response响应头content-disposition,来下载文件,如果文件有中文,就用url编码

 1         String path = this.getServletContext().getRealPath("/download/妞儿.jpg");
 2         String fileName = path.substring(path.lastIndexOf("\") + 1);
 3         //如果fileName是中文名字,那么我就要用URL编码 URLEncoder.encode(s, enc);
 4         response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
 5         InputStream in = new FileInputStream(path);
 6         OutputStream out =  response.getOutputStream();
 7         int len;
 8         byte[] buffer = new byte[1024];
 9         while((len = in.read(buffer)) > 0){
10             out.write(buffer,0,len);
11         }
12         in.close();
如果有使用请标明来源:http://www.cnblogs.com/duwenlei/
原文地址:https://www.cnblogs.com/duwenlei/p/3490518.html