springboot 大文件下載記一次生產環境因SpringBoot大文件下載導致的OOM事故


1. 使用FileSystemResource,以文件系統的絕對路徑的方式訪問靜態資源

FileSystemResource file= new FileSystemResource("c:\\xx\\xxx\\1.txt");
@GetMapping("/down")
public ResponseEntity<FileSystemResource> download(@RequestParam("uri") String uri) throws IOException {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
HttpStatus status = HttpStatus.OK;
return new ResponseEntity<>(new FileSystemResource(file), headers, status);
}

2. 使用緩存流,邊讀邊寫

@GetMapping("/down")
public void download(@RequestParam("uri") String uri, HttpServletResponse response) {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {
FileCopyUtils.copy(bufferedInputStream, bufferedOutputStream);
} catch(Exception e){

} finally {

}
}

@GetMapping("/down")
public void download(@RequestParam("uri") String uri, HttpServletResponse response) {
File file = new File(uri);
if (!file.isFile()) {
throw new ServiceException("文件不存在");
}

String filename = FilenameUtils.getName(uri);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));

try (FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream())) {


byte[] buffer_ = new byte[1024];

int n = bufferedInputStream.read(buffer_);
while(n != -1){
bufferedOutputStream.write(buffer_);
n = bufferedInputStream.read(buffer_);
}

bufferedInputStream.close();
bufferedOutputStream.close();

} catch(Exception e){

} finally {

}

}
3. 文件存儲到oss或者是七牛雲,繞過服務器下載等方式

 

參考:

https://my.oschina.net/pwh19920920/blog/4699776?tdsourcetag=s_pctim_aiomsg


————————————————
版權聲明:本文為CSDN博主「shiboyuan0410」的原創文章,遵循CC 4.0 BY-SA版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/shiboyuan0410/article/details/115209291


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM