본문 바로가기
Java/Spring Boot

파일 다운로드(HttpServletResponse, ResponseEntity)

by ddss6565 2023. 7. 16.

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);
    }
}
반응형

댓글