JAVA文件下載時亂碼有兩種狀況:java
1,下載時中文文件名亂碼瀏覽器
2,下載時由於路徑中包含中文文件名亂碼,提示找不到文件tomcat
解決方法見下面部分代碼app
response.setContentType("multipart/form-data");
String userAgent = request.getHeader("User-Agent");
String oraFileName = meetingFile.getFileName();
String formFileName=oraFileName;
// 針對IE或者以IE爲內核的瀏覽器:
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
formFileName = java.net.URLEncoder.encode(formFileName, "UTF-8");
} else {
// 非IE瀏覽器的處理:
formFileName = new String(formFileName.getBytes("UTF-8"), "ISO-8859-1");
}
response.setHeader("Content-disposition",
String.format("attachment; filename=\"%s\"", formFileName));
response.setContentType("application/vnd.ms-excel;charset=utf-8");
response.setCharacterEncoding("UTF-8");
ServletOutputStream out;
// 經過文件路徑得到File對象
File file = null;
if (meetingFile != null) {
file = new File(path + "upload/"+oraFileName);
}
(1)若是第一種亂碼類型,下載頁面遇到如下的中文亂碼問題eclipse
用如下代碼解決ide
(2)若是下載遇到第二種亂碼問題,如圖:測試
用如下代碼解決:即首先確保tomcat ,eclipse等爲utf-8編碼編碼
而後JAVA中這樣與第一種對文件名編碼分開,使它們分別編碼,互不影響。spa
注意:之前目前測試可解決火狐與IE等瀏覽器下載時的編碼問題,而針對WIN10自帶的瀏覽器不時仍會出現亂碼現象.net