1. 程式人生 > >兼容各瀏覽器的文件下載時中文名稱亂碼的解決方案

兼容各瀏覽器的文件下載時中文名稱亂碼的解決方案

exceptio 沒有 orm ioe throws keyword codes fire head

public class DownloadServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// codes..
String name = "中文名 帶空格 的測試文件.txt";
String userAgent = request.getHeader("User-Agent");
byte[] bytes = userAgent.contains("MSIE") ? name.getBytes() : name.getBytes("UTF-8"); // name.getBytes("UTF-8")處理safari的亂碼問題

name = new String(bytes, "ISO-8859-1"); // 各瀏覽器基本都支持ISO編碼
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", name)); // 文件名外的雙引號處理firefox的空格截斷問題
// codes..
}
}

這段代碼處理了文件下載時不同瀏覽器解析中文文件名所出現的亂碼問題和firefox的空格截斷問題,在IE9, chrome, opera, safari, firefox下均測試通過。

來源:https://f0rb.iteye.com/blog/1308579

    但是沒有解決我的ie9下載時的亂碼問題,做了一步修改:

response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("GBK"),"ISO8859-1"));

  修改為gbk後問題解決。

兼容各瀏覽器的文件下載時中文名稱亂碼的解決方案