Java下载文件,中文名乱码(attachment;filename=中文文件名)(Java download file, Chinese name garbled (attachment; filename = Chinese file name))

发现搜到的全部一样的方案 new String(fileName.getBytes(), “ISO8859-1”)

贴一个不一样的解决方案

使用URLEncoder.encode

1
String attachName = "这是中文名称文件.txt"//<a href="https://www.cnblogs.com/tomcatandjerry/p/11541871.html">https://www.cnblogs.com/tomcatandjerry/p/11541871.html</a>
String attachName = 
"这是中文名称文件.txt"
//<a href="https://www.cnblogs.com/tomcatandjerry/p/11541871.html">https://www.cnblogs.com/tomcatandjerry/p/11541871.html</a>
1
2
3
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition""attachment;filename=" + URLEncoder.encode(attachName, "UTF-8"));
response.setCharacterEncoding(
"utf-8"
);
response.setContentType(
"application/octet-stream"
);
response.setHeader(
"Content-Disposition"
"attachment;filename="
+ URLEncoder.encode(attachName, 
"UTF-8"
));
————————

Find all the same schemes found new string (filename. Getbytes(), “iso8859-1”)

Post a different solution

使用URLEncoder.encode

1
String attachName = "这是中文名称文件.txt"//<a href="https://www.cnblogs.com/tomcatandjerry/p/11541871.html">https://www.cnblogs.com/tomcatandjerry/p/11541871.html</a>
String attachName = 
"这是中文名称文件.txt"
//<a href="https://www.cnblogs.com/tomcatandjerry/p/11541871.html">https://www.cnblogs.com/tomcatandjerry/p/11541871.html</a>
1
2
3
response.setCharacterEncoding("utf-8");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition""attachment;filename=" + URLEncoder.encode(attachName, "UTF-8"));
response.setCharacterEncoding(
"utf-8"
);
response.setContentType(
"application/octet-stream"
);
response.setHeader(
"Content-Disposition"
"attachment;filename="
+ URLEncoder.encode(attachName, 
"UTF-8"
));