一般情况下,大家都是这样: fileName = URLEncoder.encode(fileName, "UTF-8");response.reset();response.setHeader("Content-disposition",
一般情况下,大家都是这样:
fileName = URLEncoder.encode(fileName, "UTF-8");response.reset();response.setHeader("Content-disposition", "attachment;filename=" + fileName);response.setContentType("application/octet-stream; charset=UTF-8");IoUtil.copy(inputStream, response.getOutputStream());
其实乱码就是乱在;filename=" + fileName这里,对文件名的编码设定上。
使用URLEncoder.encode(filepath,"UTF-8")虽然可以解决在提示下载框中正确显示汉字文件名的问题,并且在选择保存,然后打开的情况下,文件名称也可以正确的显示。
但是在提示下载框中,选择直接打开,则文件名称变成了类似“%E7%BB%99%E7%94%A8%E6%88%B7%E6%8F%90%E4%BE%9B%E7%9A%84%E4%B8%8B%E8%BD%BD%E6%96%87%E4%BB%B6%E5%90%8D”的样子。
为了解决这个问题,百度了好久,是这样的
String downloadfile = new String(filepath.getBytes("gb2312"),"iso8859-1");
response.addHeader("Content-Disposition","attachment;filename=" + downloadfile );
还有这样
String userAgent = request.getHeader("User-Agent");
String fORMFileName = "员工表.xls";
// 针对IE或者以IE为内核的浏览器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
} else {
// 非IE浏览器的处理:
formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",String.format("attachment; filename=\"%s\"", formFileName));
response.setContentType("multipart/form-data");
response.setCharacterEncoding("UTF-8");
发现都不能解决问题,不懈努力,崩溃边缘,最终解决
fileName = URLEncoder.encode(fileName, "UTF-8");response.reset();// fileName后面设置编码格式是重点response.setHeader("Content-disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName);response.setContentType("application/octet-stream; charset=UTF-8");IoUtil.copy(inputStream, response.getOutputStream());
完美解决!!!
来源地址:https://blog.csdn.net/m0_56324585/article/details/131577792
--结束END--
本文标题: Java下载文件,中文文件名乱码问题解决(文件名包含很多%)
本文链接: https://www.lsjlt.com/news/390468.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0