java文件下载设置中文名称(response.addHeader)

2017-12-01 12:06:59来源:cnblogs.com作者:抠脚大汉在抠脚人点击

分享
 1 protected void doPost(HttpServletRequest request, HttpServletResponse response) 2             throws ServletException, IOException { 3          String browser = ""; 4          String fileName = "测试.txt"; 6             try { 7                 browser = request.getHeader("User-Agent"); 8                 if (-1 < browser.indexOf("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) { 9                     // IE6, IE7 浏览器10                     response.addHeader("content-disposition", "attachment;filename="11                             + new String(fileName.getBytes(), "ISO8859-1"));12                 } else if (-1 < browser.indexOf("MSIE 8.0")) {13                     // IE8 14                     response.addHeader("content-disposition", "attachment;filename="15                             + URLEncoder.encode(fileName, "UTF-8"));16                 } else if (-1 < browser.indexOf("MSIE 9.0")) {17                     // IE918                     response.addHeader("content-disposition", "attachment;filename="19                             + URLEncoder.encode(fileName, "UTF-8"));20                 } else if (-1 < browser.indexOf("Chrome")) {21                     // 谷歌22                     response.addHeader("content-disposition",23                             "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));24                 } else if (-1 < browser.indexOf("Safari")) {25                     // 苹果26                     response.addHeader("content-disposition", "attachment;filename="27                             + new String(fileName.getBytes(), "ISO8859-1"));28                 } else {29                     // 火狐或者其他的浏览器30                     response.addHeader("content-disposition",31                             "attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));32                 }33             } catch (Exception e) {34                 e.printStackTrace();35             }36             InputStream in = new FileInputStream("D://test.txt");//获取文件输入流37              int len = 0;38              byte[] buffer = new byte[1024];39              OutputStream out = response.getOutputStream();40              while ((len = in.read(buffer)) > 0) {41                  out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器42              }43              in.close();44              out.flush();45              out.close();46     }

 判断各个浏览器,然后进行解码和加码

微信扫一扫

第七城市微信公众平台