當透過瀏覽器下載檔案時,需要處理不同瀏覽器對檔案名稱該如何正確編碼的問題。
可以參考[2]的實驗結果。
目前針對IE採用UrlEncode,chrome與firefox採用Mimetype base64編碼,其他未偵到的也都採用base64 :D,base64編碼可直接使用 MimeUtility.encodeText(fileName, "UTF-8", "B");即可。
範例碼如下:
String userBrowser = request.getHeader(HEADER_USER_AGENT);
if(userBrowser != null){
log.debug(String.format("User agent: %s", userBrowser));
if(userBrowser.toLowerCase().indexOf("mozilla") > -1
&& userBrowser.toLowerCase().indexOf("msie") < 0
&& userBrowser.toLowerCase().indexOf("chrome") < 0){
log.debug("Detect 'FireFox' browser");
// Mozilla/5.0 (Windows NT 6.1; WOW64; rv:25.0) Gecko/20100101 Firefox/25.0
fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
}else if(userBrowser.toLowerCase().indexOf("msie") > -1){
log.debug("Detect 'IE' browser");
// Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; WOW64; Trident/6.0; MATP)
//cosa url encoder
fileName = URLEncoder.encode(fileName);
}else{
// Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36
log.debug("Common attachment");
fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
}
}
else{
log.debug("Cannot find User-Agent header");
// encoding - the encoding to be used. Currently supported values are "B" and "Q".
// If this parameter is null, then the "Q" encoding is used if most of characters to be encoded are in the ASCII charset, otherwise "B" encoding is used.
fileName = MimeUtility.encodeText(fileName, "UTF-8", "B");
}
log.debug("Filename encoded:" + fileName);
String contentDisposition = String.format("%s ;filename=\"%s\"", valOfDisposition, fileName);
log.debug("Content diposition:" + contentDisposition);
builder.header(HEADER_CONTENT_DISPOSITION,contentDisposition);
測試檔案:
ライセンス期限切中文中文kumokura_010507.exe
Base64編碼:
=?UTF-8?B?44Op44Kk44K744Oz44K55pyf6ZmQ5YiH5Lit5paH5Lit5paHa3Vt?= =?UTF-8?B?b2t1cmFfMDEwNTA3LmV4ZQ==?=
參考:
[1]
錯誤訊息:「Internet Explorer cannot download a file (Internet Explorer 無法下載檔案)」
[2]
Unicode网页中上传下载文件时发生文件名乱码的问题