Java/Spring

Spring Boot 로 만드는 Upload와 Download Rest API 예제-04

팡스 2018. 12. 17. 15:24

이번 글에서는 파일 업로드와 다운로드에 필요한 service 단을 완성해보려고 한다.


1) Service 생성


먼저 기본 패키지 그룹에 service 패키지를 생성하고 FileUploadDownloadService 라는 클래스를 생성한다.


1
2
3
4
5
6
7
8
9
package com.pang.fileuploaddemo.service;
 
import org.springframework.stereotype.Service;
 
@Service
public class FileUploadDownloadService {
 
}
 
cs


@Service Annotation 을 잊지말고 추가하자



다음으로 파일이 저장될 디렉토리를 설정하고 디렉토리를 생성하는 소스를 추가한다.


Service가 실행될때 생성자에서 기존에 생성한 설정클래스인 FileUploadProperties 클래스로 기본 디렉토리를 설정하고 생성한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
    private final Path fileLocation;
    
    @Autowired
    public FileUploadDownloadService(FileUploadProperties prop) {
        this.fileLocation = Paths.get(prop.getUploadDir())
                .toAbsolutePath().normalize();
        
        try {
            Files.createDirectories(this.fileLocation);
        }catch(Exception e) {
            throw new FileUploadException("파일을 업로드할 디렉토리를 생성하지 못했습니다.", e);
        }
    }
cs



파일을 저장하는 소스를 작성한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
    public String storeFile(MultipartFile file) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
        
        try {
            // 파일명에 부적합 문자가 있는지 확인한다.
            if(fileName.contains(".."))
                throw new FileUploadException("파일명에 부적합 문자가 포함되어 있습니다. " + fileName);
            
            Path targetLocation = this.fileLocation.resolve(fileName);
            
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            
            return fileName;
        }catch(Exception e) {
            throw new FileUploadException("["+fileName+"] 파일 업로드에 실패하였습니다. 다시 시도하십시오.",e);
        }
    }
cs



파일을 다운로드 하는 소스를 작성한다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
    public Resource loadFileAsResource(String fileName) {
        try {
            Path filePath = this.fileLocation.resolve(fileName).normalize();
            Resource resource = new UrlResource(filePath.toUri());
            
            if(resource.exists()) {
                return resource;
            }else {
                throw new FileDownloadException(fileName + " 파일을 찾을 수 없습니다.");
            }
        }catch(MalformedURLException e) {
            throw new FileDownloadException(fileName + " 파일을 찾을 수 없습니다.", e);
        }
    }
cs



이상으로 service 단 소스를 완성했다.


다음은 controller 단 소스를 완성하고 테스트까지 진행해 보도록 하겠다.


2018/12/17 - [Java/Spring] - Spring Boot 로 만드는 Upload와 Download Rest API 예제-01

2018/12/17 - [Java/Spring] - Spring Boot 로 만드는 Upload와 Download Rest API 예제-02

2018/12/17 - [Java/Spring] - Spring Boot 로 만드는 Upload와 Download Rest API 예제-03

2018/12/17 - [Java/Spring] - Spring Boot 로 만드는 Upload와 Download Rest API 예제-05