Servlet:浏览器下载文件时文件名为乱码问题

 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         String filename = request.getParameter("filename");
 3         System.out.println(filename);
 4         String path = getServletContext().getRealPath("download/"+filename);
 5         // 将下载的文件设置成utf8编码(必须先找到文件真实路径path,再进行UTF8编码,否则服务器端找不到utf8编码后的文件名)
 6         filename = URLEncoder.encode(filename,"UTF-8");
 7         // 设置响应头,控制浏览器下载该文件
 8         response.setHeader("Content-disposition", "attachment;filename="+filename);
 9 
10         InputStream is = new FileInputStream(path);
11         OutputStream os = response.getOutputStream();
12         int len = 0;
13         byte[] buffer = new byte[1024];
14         while((len = is.read(buffer)) != -1) {
15             os.write(buffer,0,len);
16         }
17         os.close();
18         is.close();
19     }

 

posted @ 2019-10-20 14:56  AyeeX  阅读(409)  评论(0编辑  收藏  举报