最近用在做一个流程功能的文件上传下载功能时,发现部分IE浏览器上下载中文文件名文件时会出现文件名乱码的现象,使用谷歌完全没有问题,只是使用ie或以ie为内核的浏览器时会出现乱码问题,解决如下:
@GetMapping("/download")
public void download( HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "pathName",required = false)String pathName) {
String path = installService.findUrlByName(pathName);
String suffix = pathName.substring(pathName.indexOf("."),pathName.length());
if (suffix.equals(".jpg")||suffix.equals(".txt")||suffix.equals(".pdf")||suffix.equals(".png")||suffix.equals(".jpeg")){
uploadPic(response,path);
}else {
try {
downCfg(pathName, request, response);
OutputStream out;
FileInputStream inputStream = new FileInputStream(path);
out = response.getOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = inputStream.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
inputStream.close();
out.close();
out.flush();
} catch (IOException e) {
//e.printStackTrace();
}
}
}
private void downCfg(String fileName, HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {
//判断浏览器对下载的文件处理乱码问题
String userAgent = request.getHeader("User-Agent").toUpperCase();
//IE或者以IE为内核的浏览器
if (userAgent.contains("MSIE") || userAgent.contains("TRIDENT") || userAgent.contains("EDGE")) {
fileName = URLEncoder.encode(fileName, "UTF-8");
fileName = fileName.replace("+","%20");
} else {
//非IE浏览器
fileName = new String(fileName.getBytes(), "ISO8859-1");
}
response.setHeader("Content-disposition", String.format("attachment; filename=\"%s\"", fileName));
response.setContentType("application/octet-stream;charset=utf-8");
response.setCharacterEncoding("UTF-8");
}
仅供参考!