使用response实现文件下载注意点

创建web工程,使用response实现文件的下载.

在webRoot下创建download文件,里面包含要下载的文件,现在把源码贴上来,然后再说我遇到的问题

 1 public class DownLoadDemo extends HttpServlet {
 2 
 3     public void doGet(HttpServletRequest request, HttpServletResponse response)
 4             throws ServletException, IOException {
 5 
 6     String path = this.getServletContext().getRealPath("/download/倒影.jpg");
 7     System.out.println("路径是==="+path);
 8     //lastIndexOf返回的是最后一次出现的索引,截取的话必须要+1,从/的后面开始截取
 9     String filename = path.substring(path.lastIndexOf("/")+1);
10     //注意:在mac中就是/,但是在windows中,文件路径是\,是转译符,要再加上一个\,\才是:
11 //    String filename = path.substring(path.lastIndexOf("\")+1);这是在windows下的文件路径截取
12     System.out.println("文件名是==="+filename);
13 
14     //如果下载的文件是中文的话,文件需要经过URL编码
15     response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(filename,"UTF-8"));
16     InputStream in = null;
17     OutputStream out = null;
18     try {
19         in = new FileInputStream(path);
20         int len = 0;
21         byte bys[] = new byte[1024];
22         out = response.getOutputStream();
23         while((len = in.read(bys)) > 0){
24             out.write(bys, 0, len);
25         }
26     } finally {
27         if (in != null) {
28             try {
29                 in.close();
30             } catch (Exception e) {
31                 e.printStackTrace();
32             }
33         }
34      }
35     
36     }

两个需要注意的点:

1.通过文件路径获取文件名,在代码中已经说过,windows和mac的路径是不一样的,这个一定要注意,不然下载就会出错

2.当文件名是中文时,文件要通过URL编码

原文地址:https://www.cnblogs.com/losedMemory/p/6283782.html