Out Of Memory 이슈로 인해 Buffer를 사용하도록 구현되어야 함.
Buffer를 사용하지 않고 용량이 큰 파일을 다운로드 하면 파일 사이즈 만큼 메모리가 점유되어 JVM이 강제종료 됨.
HttpServletResponse
@GetMapping("/file/download")
public void fileDownload(HttpServletResponse response) throws Exception
{
FileSystemResource fileSystemResource = new FileSystemResource("C:\\test\\test.zip");
File file = fileSystemResource.getFile();
String fileName = file.getName();
String attachment = "filename=\"" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20") + "\";";
attachment += "filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20") + ";";
response.setHeader("Content-Disposition", "attachment;" + attachment);
response.setHeader("Content-Length", file.length() + "");
try(InputStream inputStream = new FileInputStream(file))
{
if(inputStream != null)
{
StreamUtils.copy(inputStream, response.getOutputStream());
response.flushBuffer();
}
}
}
ResponseEntity
@GetMapping("/file/download")
public ResponseEntity<InputStreamResource> fileDownload(HttpServletResponse response) throws Exception
{
FileSystemResource fileSystemResource = new FileSystemResource("C:\\test\\test.zip");
File file = fileSystemResource.getFile();
String fileName = file.getName();
try
{
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentLength(fileSystemResource.contentLength());
// inline, attachment, attachment; filename="filename.jpg"
ContentDisposition contentDisposition = ContentDisposition.builder("attachment")
.filename(fileName, Charset.forName("UTF-8"))
.build();
headers.setContentDisposition(contentDisposition);
return ResponseEntity.ok()
.headers(headers)
.lastModified(fileSystemResource.lastModified())
.contentLength(fileSystemResource.contentLength())
.body(new InputStreamResource(fileSystemResource.getInputStream()));
}
catch(Exception e)
{
return ResponseEntity.internalServerError()
.body(null);
}
}
반응형
'Java > Spring Boot' 카테고리의 다른 글
Spring Security Xml Config (0) | 2023.07.16 |
---|---|
Spring Security Java Config (0) | 2023.07.16 |
Spring Security 로그인 된 사용자 정보 가져오기 (0) | 2023.07.16 |
Spring Security Java에서 로그인, 로그아웃 (0) | 2023.07.16 |
Spring Boot MyBatis 설정법 (0) | 2021.06.07 |
댓글