记录一下开发中遇到的坑:
下载文件分两种,一种是从项目目录下载(一般是模板文件),另一种是本地文件目录下载(一般是用户数据文件)。
从项目目录下载
public static ResponseEntity<byte[]> downloadProjectFile(String fileLoaction) throws IOException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
Path path = Paths.get(request.getServletContext().getRealPath(fileLoaction));
if (!path.toFile().exists()) {
throw new FileNotFoundException("文件: " + path + "未被找到.");
}
byte[] body = Files.readAllBytes(path);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(FilenameUtils.getName(fileLoaction), "UTF-8"));
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
return entity;
}
从本地文件目录下载
public static ResponseEntity<byte[]> downloadFile(Path path, String fileName) throws IOException {
if (!path.toFile().exists()) {
throw new FileNotFoundException("文件: " + path + "未被找到.");
}
byte[] body = Files.readAllBytes(path);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + URLEncoder.encode(fileName, "UTF-8"));
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, HttpStatus.OK);
return entity;
}
以上两种下载都使用了 ResponseEntity ,优点是很方便使用,但是实际使用时发现,如果运行在小服务器上出现读取大文件时崩溃,原因是 ResponseEntity 会一次性把文件读入再传输。经过几次排查之后,将下载方式调整了一下,解决了问题,调整后代码如下:
从项目目录下载-2
public static void downloadProjectFile(String fileLoaction) throws IOException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
Path path = Paths.get(request.getServletContext().getRealPath(fileLoaction));
File file = path.toFile();
if (!file.exists()) {
throw new FileNotFoundException("文件: " + path + "未被找到.");
}
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(FilenameUtils.getName(fileLoaction), "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
Files.copy(path, response.getOutputStream());
response.flushBuffer();
}
从本地文件目录下载-2
public static void downloadFile(Path path, String fileName) throws IOException {
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
.getRequest();
HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
File file = path.toFile();
if (!file.exists()) {
throw new FileNotFoundException("文件: " + path + "未被找到.");
}
response.reset();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition",
"attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.addHeader("Content-Length", "" + file.length());
Files.copy(path, response.getOutputStream());
response.flushBuffer();
}