ie浏览器下载文件时文件名乱码

时间:2022-12-27 09:40:05

做一个文件下载功能时,用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();
}
}