포스트

Spring 컨트롤러에서 파일 다운로드하기

개요

Spring Framework에서 파일을 다운로드하는 작업은 꽤 자주 일어나는 시나리오 중 하나입니다. 이 글에서는 StackOverflow에서 나온 여러 가지 방법 중, 가장 효율적인 방법을 상세하게 소개하려고 합니다.

HttpServletResponse와 OutputStream 이용

첫 번째로, HttpServletResponse 객체와 OutputStream을 이용하는 방법을 살펴보겠습니다. 이들은 HTTP 응답(Response)을 제어하고, 클라이언트에게 데이터를 전송할 수 있는 자바 클래스입니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@RequestMapping("/download")
public void downloadFile(HttpServletResponse response) throws IOException {
    // 파일 경로 설정
    File file = new File("example.txt");
    
    // 헤더 설정
    response.setContentType("application/octet-stream");
    response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
    
    // 파일 전송
    try (InputStream is = new FileInputStream(file);
         OutputStream os = response.getOutputStream()) {
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = is.read(buffer)) != -1) {
            os.write(buffer, 0, bytesRead);
        }
    }
}

장점과 단점

  • 장점: 구현이 간단하고 직관적입니다.
  • 단점: 복잡한 파일 전송 로직에는 적합하지 않을 수 있습니다.

ResponseEntity 사용

두 번째 방법은 ResponseEntity를 사용하는 것입니다. 이 클래스는 HTTP 응답에 대한 상세한 정보를 담을 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
@RequestMapping("/download")
public ResponseEntity<Resource> downloadFile() {
    // 파일 경로 설정
    Path path = Paths.get("example.txt");
    Resource resource = new FileSystemResource(path);
    
    // 리턴
    return ResponseEntity.ok()
        .contentType(MediaType.parseMediaType("application/octet-stream"))
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"")
        .body(resource);
}

장점과 단점

  • 장점: HTTP 응답을 더 세밀하게 제어할 수 있습니다.
  • 단점: 코드가 약간 복잡해질 수 있습니다.

오류 상황

코드 실행 중 FileNotFoundException 같은 오류가 발생할 수 있습니다. 이 경우에는 적절한 예외 처리를 통해 해결할 수 있습니다.

결론

Spring에서 파일 다운로드를 구현하는 방법은 여러 가지가 있습니다. HttpServletResponseOutputStream을 사용하거나, ResponseEntity를 이용할 수 있으며, 각 방법에는 장점과 단점이 있습니다. 따라서 상황에 따라 적절한 방법을 선택하면 됩니다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.