본문 바로가기

IT/개발

spring 파일 업로드

매번 프로젝트에 투입될때마다 고민하고 구글링하는걸 방지하고자 작성합니다.
파일 업로드, 다운로드, 삭제에 대한 API를 정의해놓기

파일업로드는 @RequestParam으로 MultipartFile을 파라미터로 받던지
@RequestBody에 받던지 상관없고
파일을 받아서 실제 저장할 물리적 위치를 정의해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
public String upload(Long orderId, MultipartFile file) throws Exception {
//파일 path를 정의해준다.
        Path saveRepoPath = Paths.get(rootStoragePath, fileStoragePath, String.valueOf(orderId));
//파일 데이터에서 이름을 가져온다.
        String orgFileName = file.getOriginalFilename();
//파일 객체를 생성한다.
        File dest = new File(file.getOriginalFilename());
//multipartFile을 file로 변환시켜준다.
        file.transferTo(dest);
//실제 저장
        FileStorageUtils.write(saveRepoPath, orgFileName, dest);
        return saveRepoPath.toString();
}
cs

 

FileStorageUtils.class

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public static boolean write(Path filePath, String fileName, File file) throws Exception {
        boolean isSuccess = false;
        
        try {
            if(Files.notExists(filePath)) {
//디렉토리가 없으면 생성해준다.
                Files.createDirectories(filePath);
            }
            
            filePath = filePath.resolve(fileName);
//실제 byte로 변환해서 업로드!
            int byteCnt = FileCopyUtils.copy(file, filePath.toFile());
            if(file.length() == byteCnt) {
                isSuccess = true;
            }
 
        } catch (IllegalStateException | IOException e) {
            logger.error("파일 쓰기 오류 발생 :: ", e);
            throw e;
        } 
        
        return isSuccess;
    }
cs

 

완성...생각보다 간단하다.

'IT > 개발' 카테고리의 다른 글

spring file delete  (0) 2020.10.29
spring 파일 다운로드  (0) 2020.10.28
no suitable constructor found for type 에러 분석  (0) 2020.10.26
spring junit test  (0) 2020.10.16
JAVA 상대경로  (0) 2019.12.02