中文名稱下載文件亂碼,主要要做Firefox,IE和chrome這三個瀏覽器的適配。
IE瀏覽器 一直就是不走尋常路版本眾多,苦逼的就是很多程序員了,經(jīng)常要個版本瀏覽器的適配。
下面是常用瀏覽器的user-agent
IE11
Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
IE6
Mozilla/4.0 (Windows; MSIE 6.0; Windows NT 5.2)
edge
Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134
FireFox window
Mozilla/5.0 (Windows NT 6.2; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0
Firefox mac
Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0
Google window
Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.94 Safari/537.36
Google mac
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.93 Safari/537.36
Safari mac
Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_6; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27
注: 以上User-Agent有些是用魔變插件模擬出來的。
- IE瀏覽器,它們的User-AGENT可能的關(guān)鍵字有三種可能,
MSIE ,Trident ,Edge 。IE瀏覽器,使用utf-8對文件名編碼就可以了, URLEncoder.encode(fileName,“UTF8”); - Firefox 可以使用
Firefox 區(qū)分,new String(fileName.getBytes(“UTF-8”), “ISO-8859-1”); - chrome,Safari 可以使用上面兩種編碼方式。
- 第一種寫法
/**
*對下載文件名稱進(jìn)行編碼
*@param request
*@param response
*@param fileName 文件名稱
*/
public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "MSIE")||StringUtils.contains(userAgent, "Trident") || StringUtils.contains(userAgent,"Edge")){//IE 瀏覽器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}else{//火狐,google等其他瀏覽器
finalFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//\" 解決Firefox下載英文+中文組合的文件名的問題
} catch (UnsupportedEncodingException e) {
}
}
- 第二種寫法
/**
*對下載文件名稱進(jìn)行編碼
*@param request
*@param response
*@param fileName 文件名稱
*/
public void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
String userAgent = request.getHeader("USER-AGENT");
try {
String finalFileName = null;
if(StringUtils.contains(userAgent, "Firefox")){//火狐瀏覽器
finalFileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
}else{//IE,google等其他瀏覽器
finalFileName = URLEncoder.encode(fileName,"UTF8");
}
response.setHeader("Content-Disposition", "attachment; filename=\"" + finalFileName + "\"");//\" 解決Firefox下載英文+中文組合的文件名的問題
} catch (UnsupportedEncodingException e) {
}
}
|