티스토리 뷰

Spring에서 파일 업로드 REST API를 만들기 위해서는 HTTP POST와 MultipartFile을 인자로 간단하게 만들 수 있습니다.

 

아래와 같이 컨트롤러에 Post endpoint를 만든 후, MultipartFile을 인자로 넣어줍니다.

 

그리고 로직을 구현할 Service 빈에 MultipartFile 객체를 넘겨줍니다.

@RestController
public class UploadController {

    UploadFileService uploadFileService;

    public UploadController(UploadFileService uploadFileService) {
        this.uploadFileService = uploadFileService;
    }
    
    @PostMapping("/uploadFile")
    public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file){
        return ResponseEntity.ok(uploadFileService.uploadFile(file));
    }
}

 

서비스 빈에서는 해당 파일에 대한 정보를 가져오고, 파일을 서버에 저장하는 로직을 구현하였습니다.

이때 파일 관련 사용한 함수는 아래와 같습니다.

file.getContentType()

: 업로드한 파일의 확장자 값을 체크합니다.( csv 파일의 경우, text/csv 값이 리턴 됩니다. )

file.getOriginalFilename()

: 업로드한 파일 이름을 리턴합니다.

file.getSize()

: 업로드한 파일의 크기(byte)를 리턴합니다.

Files.copy()

: file inputStream으로 원하는 경로에 파일을 저장할 수 있습니다.

@Service
public class UploadFileService {
    private String dir = "/tmp";

    private Path fileDir;

    private final String TYPE_CSV = "text/csv";

    @PostConstruct
    public void postConstruct() {
        fileDir = Paths.get(dir).toAbsolutePath().normalize();

        try {
            Files.createDirectories(fileDir);
        } catch (IOException e) {
        }
    }

    public UploadFile uploadFile(MultipartFile file){
        if(TYPE_CSV.equals(file.getContentType()) == false){
        }
        String uploadFileName = StringUtils.cleanPath(file.getOriginalFilename());

        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(file.getInputStream(), "UTF-8"));
        } catch (IOException e) {
        }

        String realName = UUID.randomUUID().toString() + "_" + uploadFileName;
        Path targetLocation = fileDir.resolve(realName);
        try {
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
        } catch (IOException e) {
        }

        return UploadFile.builder()
                .displayName(uploadFileName)
                .size(file.getSize())
                .count(fileTargetCount)
                .build();
    }
}

 

Postman으로 파일업로드 API 테스트를 해보겠습니다.

HTTP POST를 선택하고, URI를 입력 후 Body에 file키 값을 입력하고 타입을 File로 선택을 합니다.

그러면 Value에서 Select Files라고 로컬의 파일을 선택할 수 있도록 버튼이 생성 됩니다.

이를 눌러 업로드할 파일을 선택하여 Send를 눌러 API 요청을 해주면 응답을 받게 됩니다.

{
    "id": 3,
    "displayName": "upload_svc_no_100.csv",
    "size": 6601,
    "count": 100,
    "uploadDateTime": "2021-08-26"
}

 

댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/05   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함