public static void download(HttpServletRequest request, HttpServletResponse response, File file, String fileName) {
log.info("下载文件path=[{}],name=[{}]", file.getAbsoluteFile(), fileName);
if (StringUtils.isNotBlank(fileName)) {
//设置文件路径
if (file.exists()) {
response.reset();
response.setContentType("application/octet-stream");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
response.setContentLength((int) file.length());
String newFileName;
try {
String header = request.getHeader("User-Agent").toUpperCase();
if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
newFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8.name());
newFileName = newFileName.replace("+", "%20"); //IE下载文件名空格变+号问题
} else {
newFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
} catch (Exception e) {
log.error("文件名编码处理异常", e);
newFileName = new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
}
response.setHeader("Content-Disposition", "attachment;filename=" + newFileName);
byte[] buffer = new byte[2048];
try (FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream()) {
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
} catch (Exception e) {
log.error("download file=[{}] error", newFileName, e);
throw new BusinessException(ResultCode.INTERACT_DOWNLOAD_ERROR);
}
} else {
throw new BusinessException(ResultCode.FILE_NOT_EXISTS);
}
}
}
SpringMVC文件下载IE乱码
最新推荐文章于 2022-07-12 11:37:10 发布