반응형

오늘은 Spring Boot에서 RESTful API를 통해 파일 업로드 기능을 구현하는 방법에 대해 알아보겠습니다. 파일 업로드는 사용자로부터 이미지를 업로드받거나 문서를 제출받는 등의 작업에서 사용됩니다.


1. 파일 업로드를 위한 기본 설정

Spring Boot에서 파일 업로드를 구현하기 위해서는 아래와 같은 설정을 진행해야 합니다.


(1) 의존성 추가

spring-boot-starter-web 의존성은 이미 포함되어 있다면 추가 작업이 필요하지 않습니다.

(2) application.properties 설정

업로드된 파일을 저장할 디렉토리를 지정합니다.

spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB
file.upload-dir=uploads/

위 설정은 최대 파일 크기를 5MB로 제한하고, 업로드된 파일을 uploads 디렉토리에 저장하도록 지정합니다.


2. 파일 업로드 API 구현

(1) Controller 작성

MultipartFile을 사용하여 파일 데이터를 받아옵니다.

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@RestController
@RequestMapping("/api/files")
public class FileUploadController {

    @Value("${file.upload-dir}")
    private String uploadDir;

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file) {
        try {
            // 파일 저장 경로 설정
            Path filePath = Paths.get(uploadDir + file.getOriginalFilename());
            Files.createDirectories(filePath.getParent()); // 디렉토리 생성
            Files.write(filePath, file.getBytes()); // 파일 저장

            return new ResponseEntity<>("File uploaded successfully: " + file.getOriginalFilename(), HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>("File upload failed.", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}

3. 파일 업로드 API 테스트

(1) Postman으로 테스트

  • Endpoint: POST /api/files/upload
  • Body: Form-Data
    • Key: file
    • Value: 업로드할 파일 선택

(2) 응답 예시

성공적으로 업로드되었을 경우:

{
    "message": "File uploaded successfully: example.txt"
}

파일 업로드 실패 시:

{
    "message": "File upload failed."
}

4. 업로드된 파일 확인

파일은 uploads 디렉토리 아래에 저장됩니다. 디렉토리 위치는 프로젝트 루트 경로에 상대적이거나 설정 파일에서 절대 경로를 지정할 수도 있습니다.


5. 예외 처리

업로드된 파일이 없거나 크기가 제한을 초과했을 경우 예외를 처리합니다.

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.http.ResponseEntity;

@ControllerAdvice
public class FileUploadExceptionAdvice {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public ResponseEntity<String> handleMaxSizeException(MaxUploadSizeExceededException exc) {
        return ResponseEntity.badRequest().body("File size exceeds the maximum limit!");
    }
}

6. 확장자 제한 및 검증

특정 파일 유형만 허용하도록 확장자를 검증합니다.

private boolean isValidFileType(String filename) {
    String[] allowedExtensions = {"jpg", "png", "pdf"};
    String fileExtension = filename.substring(filename.lastIndexOf(".") + 1);
    for (String extension : allowedExtensions) {
        if (extension.equalsIgnoreCase(fileExtension)) {
            return true;
        }
    }
    return false;
}

컨트롤러에서 파일 검증을 추가합니다.

if (!isValidFileType(file.getOriginalFilename())) {
    return new ResponseEntity<>("Invalid file type.", HttpStatus.BAD_REQUEST);
}

7. 실습 결과

이제 Spring Boot RESTful API를 통해 파일 업로드를 구현할 수 있습니다. 업로드된 파일을 저장하고, 적절한 예외를 처리하며, 필요에 따라 파일 유형을 제한하여 안전성을 강화할 수 있습니다.

반응형

+ Recent posts