1. 程式人生 > 實用技巧 >Mac Safari瀏覽器下載檔案亂碼完美解決

Mac Safari瀏覽器下載檔案亂碼完美解決

就在剛剛,小程式做下載xlsx檔案時,測試發現Safari瀏覽器下載的檔名稱出現亂碼。

後臺java程式碼是這樣的

response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name + "." + extName, "UTF-8") );

最終在網上找到了解決方案

/**
* <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://www.jianshu.com/p/7b82dca23b06

糾其原因,主要是下載Header頭不符合RFC規範導致。參考文章:http://www.sohu.com/a/334506221_463987