본문 바로가기
스프링 관련/스프링

스프링 Rest API로 전달 된 파일 저장하기 (MultipartFile 사용)

by 문자메일 2023. 3. 5.

 

 

 

Controller

    @PostMapping("/files")
    public ResponseDTO<Void> upload(MultipartFile file){
        fileStorageService.save(file);
        return ok();
    }

 

FileStorageService.java

package com.fastcampus.loan.service;

import org.springframework.web.multipart.MultipartFile;

public interface FileStorageService {

    void save(MultipartFile file);
}

 

FileStorageServiceImpl.java


@Service
@RequiredArgsConstructor
public class FileStorageServiceImpl implements FileStorageService{

    @Value("${spring.servlet.multipart.location}")
    private String uploadPath;

    @Override
    public void save(MultipartFile file) {
        try{
            Files.copy(file.getInputStream(), Paths.get(uploadPath).resolve(file.getOriginalFilename()),
                    StandardCopyOption.REPLACE_EXISTING);
        } catch (Exception e) {
            throw new BaseException(ResultType.SYSTEM_ERROR);
        }
    }
}

 

application.yml

  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 10MB
      location: ./file

댓글