使用 java.net.URLEncoder 编码下载文件名后会将空格替换为+,导致前端处理文件名时不能还原文件名的空格。
String s = "文件 -文件1";
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8);
结果为:%E6%96%87%E4%BB%B6+-%E6%96%87%E4%BB%B61,空格被替换为+,而不是%20,JS使用DecodeURIComponent得到 “文件+-文件1”。
查看源码可得 java.net.URLEncoder 实现的是 application/x-www-form-urlencoded https://www.w3.org/TR/html4/interact/forms.html#h-17.13.4。
处理方式为:
URLEncoder.encode("Hello World", "UTF-8").replace("+", "%20");
UriUtils.encode(fileName, StandardCharsets.UTF_8.name());
参考:https://stackoverflow.com/questions/4737841/urlencoder-not-able-to-translate-space-character#
https://www.zhihu.com/question/38753917
原文:https://www.cnblogs.com/mmdxg/p/11642483.html