实例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String browser = "";
String fileName = "测试.txt";
try {
browser = request.getHeader("User-Agent");
if (-1 < browser.indexOf ("MSIE 6.0") || -1 < browser.indexOf("MSIE 7.0")) {
// IE6, IE7 浏览器
response.addHeader("content-disposition", "attachment;filename="
+ new String(fileName.getBytes(), "ISO8859-1"));
} else if (-1 < browser.indexOf("MSIE 8.0")) {
// IE8
response.addHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("MSIE 9.0")) {
// IE9
response.addHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Chrome")) {
// 谷歌
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
} else if (-1 < browser.indexOf("Safari")) {
// 苹果
response.addHeader("content-disposition", "attachment;filename="
+ new String(fileName.getBytes(), "ISO8859-1"));
} else {
// 火狐或者其他的浏览器
response.addHeader("content-disposition",
"attachment;filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8"));
}
} catch (Exception e) {
e.printStackTrace();
}
InputStream in = new FileInputStream("D:\\test.txt");//获取文件输入流
int len = 0 ;
byte[] buffer = new byte[1024];
OutputStream out = response .getOutputStream();
while (( len = in .read(buffer)) > 0) {
out.write(buffer,0,len);//将缓冲区的数据输出到客户端浏览器
}
in.close();
out.flush();
out.close();
}
|
判断各个浏览器,然后进行解码和加码。
以上这篇java文件下载设置中文名称的实例(response.addHeader)就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/zjq-kjdh/archive/2017/12/01/7940493.html