码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-12-01 11:48:25      阅读:191      评论:0      收藏:0      [点我收藏+]

标签:agent   urlencode   safari   bsp   read   谷歌   encoder   输出   enc   

 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                     // IE9
18                     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     }

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

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

标签:agent   urlencode   safari   bsp   read   谷歌   encoder   输出   enc   

原文地址:http://www.cnblogs.com/zjq-kjdh/p/7940493.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!