使用Servlet实现文件下载功能时,使用IE下载出现文件名乱码;
网上常见的解决办法是通过"user-agen"来判断浏览器:
if (req.getHeader("user-agent").toLowerCase().contains("msie")) {
// IE
filename = URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE
filename = new String(filename.getBytes("UTF-8"), "iso-8859-1");
}
但是在Windows 10 中 用户代理字符串已经修改了 不在是"msie"了
- 兼容("兼容")和浏览器 ("MSIE") 令牌已删除。
- "like Gecko" 令牌已添加(以便与其他浏览器一致)。
- 浏览器版本现在由新版本 ("rv") 令牌报告。
win 10 ie user-agent
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko ie 11
win 10 edge user-agent
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko ie 11
win 10 edge user-agent
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36 Edge/14.14393 edge
所以就不能在使用msie判断是否是IE 浏览器.
String userAgent = req.getHeader("user-agent").toLowerCase(); if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// fe
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}
项目示例代码:
try {
String fileName = attachmentFile.originalName();
String userAgent = request.getHeader("user-agent").toLowerCase();
if (userAgent.contains("msie") || userAgent.contains("like gecko") ) {
// win10 ie edge 浏览器 和其他系统的ie
fileName = URLEncoder.encode(fileName, "UTF-8");
} else {
// fe
fileName = new String(fileName.getBytes("utf-8"), "iso-8859-1");
}
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition",
"attachment;fileName=" + fileName);
String path = attachmentFile.path();
InputStream inputStream = new FileInputStream(new File(path)); OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
} // 这里主要关闭。
os.close(); inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}