项目中有用到文件下载功能,之前在处理下载时对IE浏览器下文件下载名进行过处理,测试也没有问题,
但是功能上线后,业务反馈IE11文件下载文件名依然乱码。打印User-Agent字符串如下:
IE11 User-Agent字符串:Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko
IE6~IE10版本的User-Agent字符串:Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.0; Trident/6.0)
IE浏览器在IE11,更改了User-Agent字符串格式内容,所以针对IE11,做一下判断即可:
//下载文件,并处理文件名乱码
public void downloadFile(HttpServletRequest request,HttpServletResponse response){
String path = request.getSession().getServletContext().getRealPath("/upload/文档1.doc");
// path是根据日志路径和文件名拼接出来的
File file = new File(path);
//获取日志文件名称
String filename = file.getName();
try {
//判断是否是IE11
Boolean flag= request.getHeader("User-Agent").indexOf("like Gecko")>0;
if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") >0||flag){
filename = URLEncoder.encode(filename, "UTF-8");//IE浏览器
}else {
//先去掉文件名称中的空格,然后转换编码格式为utf-8,保证不出现乱码,
//这个文件名称用于浏览器的下载框中自动显示的文件名
filename = new String(filename.replaceAll(" ", "").getBytes("UTF-8"), "ISO8859-1");
//firefox浏览器
//firefox浏览器User-Agent字符串:
//Mozilla/5.0 (Windows NT 6.1; WOW64; rv:36.0) Gecko/20100101 Firefox/36.0
}
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer;
buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" +filename);
response.addHeader("Content-Length", "" + file.length());
OutputStream os = response.getOutputStream();
response.setContentType("application/octet-stream");
os.write(buffer);// 输出文件
os.flush();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}