Spring Boot로 파일 업로드 및 다운로드 구현하기
Overview
Spring Boot를 사용하여 파일 업로드 및 다운로드 기능을 구현하는 것은 웹 애플리케이션에서 자주 필요로 하는 기능입니다. 파일 업로드는 사용자로부터 서버로 파일을 전송하는 기능을 제공하며, 파일 다운로드는 서버에서 사용자에게 파일을 제공하는 기능입니다. 이 과정에서 파일의 저장, 접근, 보안 등을 고려해야 합니다.
아래에서 Spring Boot를 사용하여 파일 업로드 및 다운로드를 구현하는 방법을 자세히 설명하겠습니다.
1. 파일 업로드 기능 구현
1.1. 의존성 추가
파일 업로드 기능을 구현하기 위해 먼저 spring-boot-starter-web
의존성을 프로젝트에 추가해야 합니다. Maven을 사용하는 경우 pom.xml
파일에 다음과 같이 추가합니다:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
Gradle을 사용하는 경우 build.gradle
파일에 다음과 같이 추가합니다:
implementation 'org.springframework.boot:spring-boot-starter-web'
1.2. 컨트롤러 클래스 작성
파일 업로드를 처리하는 컨트롤러 클래스를 작성합니다. 예를 들어, FileUploadController
라는 클래스를 생성하고 다음과 같은 코드를 작성합니다:
package com.example.fileupload;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
@RestController
public class FileUploadController {
private static final String UPLOAD_DIR = "uploads";
static {
File uploadDir = new File(UPLOAD_DIR);
if (!uploadDir.exists()) {
uploadDir.mkdir();
}
}
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
Path path = Paths.get(UPLOAD_DIR, fileName);
try {
Files.write(path, file.getBytes());
} catch (IOException e) {
e.printStackTrace();
return "파일 업로드 실패";
}
return "파일 업로드 성공: " + ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/uploads/")
.path(fileName)
.toUriString();
}
}
- 업로드 디렉토리 생성:
UPLOAD_DIR
상수에 정의된 경로에 디렉토리를 생성합니다. - 파일 저장:
Files.write()
메서드를 사용하여 업로드된 파일을 지정한 디렉토리에 저장합니다. - 파일 다운로드 URL 제공:
ServletUriComponentsBuilder
를 사용하여 파일 다운로드를 위한 URL을 생성합니다.
1.3. 애플리케이션 설정
파일 업로드 처리와 관련된 설정을 application.properties
파일에 추가할 수 있습니다:
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB
- max-file-size: 업로드할 파일의 최대 크기 설정
- max-request-size: 전체 요청의 최대 크기 설정
2. 파일 다운로드 기능 구현
2.1. 컨트롤러 클래스 추가
파일 다운로드를 처리하기 위한 컨트롤러 메서드를 추가합니다. 위의 FileUploadController
클래스에 다음과 같은 메서드를 추가합니다:
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
@GetMapping("/download")
public ResponseEntity<Resource> downloadFile(@RequestParam("filename") String filename) {
File file = new File(UPLOAD_DIR, filename);
if (!file.exists()) {
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(null);
}
Resource resource = new FileSystemResource(file);
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
.body(resource);
}
- 파일 존재 여부 확인: 요청된 파일이 서버에 존재하는지 확인합니다.
- 파일 리소스 생성:
FileSystemResource
를 사용하여 파일 리소스를 생성합니다. - 응답 헤더 설정:
Content-Disposition
헤더를 설정하여 파일을 다운로드하도록 지시합니다.
3. 예외 처리
파일 업로드 및 다운로드 중 발생할 수 있는 예외를 처리하기 위해 @ExceptionHandler
를 사용할 수 있습니다. 예를 들어:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ResponseEntity<String> handleMaxSizeException(MaxUploadSizeExceededException exc) {
return ResponseEntity.status(HttpStatus.EXCESSIVE_CONTENT)
.body("파일 크기가 너무 큽니다.");
}
}
- MaxUploadSizeExceededException: 파일 크기가 설정된 최대 크기를 초과할 때 발생하는 예외입니다.
4. 보안 고려 사항
파일 업로드 및 다운로드 기능을 구현할 때 보안에도 신경 써야 합니다. 다음은 몇 가지 보안 고려 사항입니다:
- 파일 이름 검증: 사용자로부터 받은 파일 이름을 검증하여 디렉토리 트래버설 공격을 방지합니다.
- 파일 타입 검증: 업로드된 파일의 타입을 검증하여 악성 파일이 업로드되는 것을 방지합니다.
- 경로 제어: 파일 저장 및 다운로드 시 경로를 제어하여 서버의 민감한 파일에 접근하지 않도록 합니다.
참고문서
위의 설명을 통해 Spring Boot로 파일 업로드 및 다운로드 기능을 구현하는 방법을 자세히 이해할 수 있을 것입니다. 각 단계별로 필요한 설정과 구현 방법을 설명하였으니, 실제 프로젝트에 적용해 보세요.
'Study Information Technology' 카테고리의 다른 글
파이썬의 weakref 모듈을 사용한 약한 참조 구현 (0) | 2024.08.21 |
---|---|
Spring Boot와 Kubernetes 완벽한 통합 가이드 (0) | 2024.08.21 |
Spring Boot의 Bean 생명주기 이해하기 (0) | 2024.08.21 |
협력적인 다중 로봇 시스템 개발 (15) | 2024.08.21 |
Python의 pathlib 객체 지향 파일 시스템 경로 관리의 간소화 (0) | 2024.08.21 |