SoFunction
Updated on 2025-04-07

Java solution to download files with Chinese file names (file names contain a lot of %)

Issue of garbled Chinese file names in Java download files

Generally speaking, this is how everyone

fileName = (fileName, "UTF-8");
();
("Content-disposition", "attachment;filename=" + fileName);
("application/octet-stream; charset=UTF-8");
(inputStream, ());

In fact, garbled code means scrambling; filename=" + fileName here, the encoding setting of the file name.

Although using (filepath,"UTF-8") can solve the problem of correctly displaying the Chinese character file name in the prompt download box, and when selecting Save and then opening, the file name can also be displayed correctly.

However, in the prompt download box, select Open directly, and the file name becomes similar.

“%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”

To solve this problem

Baidu has been doing this for a long time, it's like this

String downloadfile = new String(("gb2312"),"iso8859-1");
("Content-Disposition","attachment;filename=" + downloadfile );

And so

String userAgent = ("User-Agent");
String formFileName = "Employee Table.xls";

// For IE or browsers with IE as the kernel:if (("MSIE") || ("Trident")) {
formFileName = (formFileName, "UTF-8");
} else {
// Non-IE browser processing:formFileName = new String(("UTF-8"), "ISO-8859-1");
}
("Content-disposition",("attachment; filename=\"%s\"", formFileName));
("multipart/form-data");
("UTF-8");

No matter how you find it, you can't solve the problem, work tirelessly, and collapse on the verge of collapse

Final solution

fileName = (fileName, "UTF-8");
();
// Setting the encoding format after fileName is the key("Content-disposition", "attachment;filename="+fileName+";"+"filename*=utf-8''"+fileName);
("application/octet-stream; charset=UTF-8");
(inputStream, ());

Perfect solution! ! !

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.