ie瀏覽器下載文件時文件名亂碼


做一個文件下載功能時,用ie瀏覽器下載時文件名亂碼,火狐和谷歌正常,修改后ie顯示正常,修改方法如下:

@RequestMapping(value = "fileDownload", method = { RequestMethod.GET })
@ResponseBody
public void fileDownload(String filepath,HttpServletResponse response,HttpServletRequest request) {

File file = new File(filepath);
String filename;
try {
int n=filepath.lastIndexOf("/");
int m = filepath.lastIndexOf("\\");
int nn = n>m?n:m;
filename = filepath.substring(nn+1);
// 獲得請求頭中的User-Agent
String agent = request.getHeader("User-Agent").toUpperCase();
//解決ie下載時文件名亂碼的問題
if (agent.contains("MSIE") || agent.contains("TRIDENT") || agent.contains("EDGE")) {   //判斷是否是ie瀏覽器
filename = URLEncoder.encode(filename, "utf-8");
}else{
filename = new String(filename.getBytes(), "iso-8859-1");
}


response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename="+filename);
FileInputStream fileInputStream = new FileInputStream(file);
byte[] by = new byte[fileInputStream.available()];
fileInputStream.read(by);
OutputStream outputStream = response.getOutputStream();
outputStream.write(by);
fileInputStream.close();
outputStream.close();

} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM