在 MSIE 中使用 base64 对文件名进行编码

Filename encoding with base64 in MSIE

我有一个方法:

  private String encodeFileAttachment(HttpServletRequest request, String filename) throws IOException {
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("Mozilla") && !userAgent.contains("MSIE")) {
    return "=?UTF-8?B?" + new String(Base64.encodeBase64(filename.getBytes("UTF-8")), "UTF-8") + "?=";
} else {
    return filename = URLEncoder.encode(filename, "UTF-8");
 }
}

文件名如:

sss zzz ddd.png

firefox return 像这样: 但是 msie return

所以可能编码方法将“”更改为“+” 该问题仅出现在 Internet Explorer 中。有人能告诉我为什么吗?

这符合预期。 URLEncoder 实现了关于如何以 HTML 形式编码 URL 的 HTML 规范。

来自 javadocs:

This class contains static methods for converting a String to the application/x-www-form-urlencoded MIME format.

并来自 HTML 规范:

    1. Control names and values are escaped. Space characters are replaced by `+'

解决方案:

URLEncoder.encode(filename, "utf-8").replaceAll("\+", " ");