各瀏覽器下載文件名不亂碼的解決辦法

在項目中發現,使用Safari下載中文名文件的時候,下載的文件名是亂碼的問題。可是這個問題在IE,Firefox,Chrome中是沒有的。原先覺得是Safari的bug,可是細細研究之下你會發現這個簡單的文件下載問題在HTTP協議裏經歷了多少波折。java

這裏直接貼出java代碼shell

/**
* <pre>
* 瀏覽器下載文件時須要在服務端給出下載的文件名,當文件名是ASCII字符時沒有問題
* 當文件名有非ASCII字符時就有可能出現亂碼
*
* 這裏的實現方式參考這篇文章
* http://blog.robotshell.org/2012/deal-with-http-header-encoding-for-file-download/
*
* 最終設置的response header是這樣:
*
* Content-Disposition: attachment;
*                      filename="encoded_text";
*                      filename*=utf-8''encoded_text
*
* 其中encoded_text是通過RFC 3986的「百分號URL編碼」規則處理過的文件名
* </pre>
* @param response
* @param filename
* @return
*/
public static void setFileDownloadHeader(HttpServletResponse response, String filename) {
  String headerValue = "attachment;";
  headerValue += " filename=\"" + encodeURIComponent(filename) +"\";";
  headerValue += " filename*=utf-8''" + encodeURIComponent(filename);
  response.setHeader("Content-Disposition", headerValue);
}

/**
* <pre>
* 符合 RFC 3986 標準的「百分號URL編碼」
* 在這個方法裏,空格會被編碼成%20,而不是+
* 和瀏覽器的encodeURIComponent行爲一致
* </pre>
* @param value
* @return
*/
public static String encodeURIComponent(String value) {
  try {
    return URLEncoder.encode(value, "UTF-8").replaceAll("\\+", "%20");
  } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    return null;
  }
}

轉載自:https://segmentfault.com/a/1190000005994758segmentfault

感謝大神解決長久以來的問題。瀏覽器

相關文章
相關標籤/搜索