如何解决java下载文件时出现中文文件名乱码问题?
发布时间:2020-05-21 22:58:47
来源:亿速云
阅读:116
作者:鸽子
解决方法:
1、sping-mvc.xml部分代码:
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
2、FileController.java中文文件名获取代码:
获取浏览器格式,根据不同浏览器控制文件名编码格式。String userAgent = request.getHeader("User-Agent");//获取浏览器名(IE/Chome/firefox)
if(userAgent.contains("MSIE")||userAgent.contains("Trident")) {//针对IE或IE为内核的浏览器
fileName=java.net.URLEncoder.encode(fileName,"UTF-8");
}else {
fileName=new String(fileName.getBytes("UTF-8"),"ISO-8859-1");//谷歌控制版本
}
headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名
其他浏览器控制字符格式:(详细)String userAgent = request.getHeader("User-Agent");//获取浏览器名(IE/Chome/firefox)
if (userAgent.contains("firefox")) {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
} else if (userAgent.contains("MSIE")) {
fileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
}else if (userAgent.contains("CHROME")) {
fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
}
headers.setContentDispositionFormData("attachment", fileName);// 默认下载文件名为原始文件名