修复不同浏览器下附件中文名乱码的bug

采用[RFC 6266]定义的标注写法,兼容市面上所有主流浏览器
详情请浏览本人原创文章:https://segmentfault.com/a/1190000023601065
This commit is contained in:
zhengxl5566
2020-08-14 15:05:13 +08:00
parent d957acd899
commit b369317800
2 changed files with 47 additions and 8 deletions

View File

@ -7,7 +7,9 @@ import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文件处理工具类
@ -139,4 +141,37 @@ public class FileUtils extends org.apache.commons.io.FileUtils
}
return filename;
}
/**
* 下载文件名重新编码
*
* @param response 响应对象
* @param realFileName 真实文件名
* @return
*/
public static void setAttachmentResponseHeader(HttpServletResponse response,String realFileName) throws UnsupportedEncodingException {
String percentEncodedFileName = percentEncode(realFileName);
StringBuilder contentDispositionValue = new StringBuilder();
contentDispositionValue.append("attachment; filename=")
.append(percentEncodedFileName)
.append(";")
.append("filename*=")
.append("utf-8''")
.append(percentEncodedFileName);
response.setHeader("Content-disposition",
contentDispositionValue.toString());
}
/**
* 百分号编码工具方法
*
* @param s 需要百分号编码的字符串
* @return 百分号编码后的字符串
*/
public static String percentEncode(String s) throws UnsupportedEncodingException {
String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
return encode .replaceAll("\\+", "%20");
}
}