shizilukou123

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

分类:

技术点:

相关文章:

  • 2021-11-17
  • 2021-12-27
  • 2021-12-27
  • 2021-08-26
  • 2021-10-15
  • 2021-11-24
猜你喜欢
  • 2021-12-27
  • 2021-11-21
  • 2021-11-10
  • 2021-11-24
  • 2021-10-19
  • 2021-09-25
  • 2021-05-06
相关资源
相似解决方案