我创建了一个下载文件的 Controller。
我直接调用 ByteArrayOutputStream.writeTo(response.getOutputStream)
响应下载的文件,目前功能正常,文件可以下载。
我的问题是,对于大文件而言,ByteArrayOutputStream.writeTo()
方法对内存是否安全?例如,下载大文件会不会导致 java.lang.OutOfMemoryError
内存溢出异常?
Controller 代码如下:
@RequestMapping(value = "download/{name}", method = RequestMethod.GET)
public void download(@PathVariable("name") final String name, HttpServletResponse response) throws Exception {
try (ByteArrayOutputStream outputStream = ... /* 我的 ByteArrayOutputStream */) {
// 获取文件大小
int size = outputStream.size();
// filename
String filename = name;
response.setContentType("application/pdf");
response.setHeader(HttpHeaders.ACCESS_CONTROL_EXPOSE_HEADERS, HttpHeaders.CONTENT_DISPOSITION);
response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + filename);
response.setHeader("filename", filename);
response.setContentLength(size);
response.setStatus(200);
// write directly to response
outputStream.writeTo(response.getOutputStream());
response.flushBuffer();
} catch (RuntimeException e) {
throw new RuntimeException(e);
}
}