現場還原,一下是下載大文件出現內存溢出的代碼:
@RequestMapping(value = "/downLoadBackupFile")
public ResponseEntity<byte[]> downloadBackupFile(Integer id, HttpServletResponse response) throws Exception{
String path = eqm.findAddr(id);
File file = new File(path);
String fileName = file.getName();
byte[] body = null;
InputStream is = new FileInputStream(file);
body = new byte[is.available()]; // 報錯顯示該行出現內存溢出問題,new了一個非常大的byte數組
is.read(body);
HttpHeaders headers = new HttpHeaders();
headers.add("Content-Disposition", "attchement;filename=" + fileName);
HttpStatus statusCode = HttpStatus.OK;
ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
return entity;
}
應該修改為:
@RequestMapping(value = "/downLoadBackupFile", method = RequestMethod.GET)
public void downloadBackupFile(Integer id, HttpServletResponse response) throws Exception{
String path = eqm.findAddr(id);
File file = new File(path);
String fileName = file.getName();
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attchement;filename=" + fileName);
response.setHeader("Content-Length", file.length() + "");
InputStream bfis = new BufferedInputStream(new FileInputStream(file));
OutputStream ops = new BufferedOutputStream(response.getOutputStream());
byte[] body = new byte[1024];
int i = -1;
while ((i = bfis.read(body)) != -1){
ops.write(body, 0, i);
}
bfis.close();
ops.flush();
ops.close();
}