最近因項目需要做一個struts2下載功能,但是老是因為在做一些get請求的中文編碼困擾,以下是解決方法
1. encodeURI將文本以utf-8的編碼,具體參見隨筆js對文字進(jìn)行編碼涉及3個函數(shù):escape,encodeURI,encodeURIComponent的區(qū)別
例:encodeURI("download.action?filenames="+filenames+"&filepaths="+filepaths);
2.但后臺與用戶交互的時候,如彈出下載對話時要想正確的顯示中文文件名,我們需要對字端再次編碼 也就是對get方法進(jìn)行編碼設(shè)置,否則中文名文件將出現(xiàn)亂碼,或無法下載的情況
例:public String getFilename() {
try {
return new String(filename.getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return filename;
}
}
3. 配置tomcat/conf/server.xml
如: <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
1. encodeURI將文本以utf-8的編碼,具體參見隨筆js對文字進(jìn)行編碼涉及3個函數(shù):escape,encodeURI,encodeURIComponent的區(qū)別
例:encodeURI("download.action?filenames="+filenames+"&filepaths="+filepaths);
2.但后臺與用戶交互的時候,如彈出下載對話時要想正確的顯示中文文件名,我們需要對字端再次編碼 也就是對get方法進(jìn)行編碼設(shè)置,否則中文名文件將出現(xiàn)亂碼,或無法下載的情況
例:public String getFilename() {
try {
return new String(filename.getBytes(), "ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return filename;
}
}
3. 配置tomcat/conf/server.xml
如: <Connector port="8080" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />
名稱: ?4C.ESL | .↗Evon
口號: 遇到新問題?先要尋找一個方案乄而不是創(chuàng)造一個方案こ
mail: 聯(lián)系我