본문 바로가기

개발일지

20231228 - 스프링 S3 사용하기

S3를 이용해서 파일을 첨부하고 다운로드할 수 있는 기능을 구현하기로 했다. 우선 S3에서 버킷을 만든 후 스프링에서 필요한 코드를 구현했다.

// application.properties
aws.s3.bucket = 버킷 이름
aws.s3.stack.auto = false
aws.s3.region.static = ap-northeast-2
aws.s3.credentials.accessKey = 액세스 키
aws.s3.credentials.secretKey = 비밀 액세스 키

 

다음은 S3Config 클래스이다.

@Configuration
public class S3Config {
    @Value("${aws.s3.credentials.accessKey}")
    private String accessKey;

    @Value("${aws.s3.credentials.secretKey}")
    private String secretKey;

    @Value("${aws.s3.region.static}")
    private String region;

    @Bean
    public AmazonS3Client amazonS3Client(){
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

        return (AmazonS3Client) AmazonS3ClientBuilder
                .standard()
                .withRegion(region)
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .build();
    }
}

BasicAWSCredentials 객체는 AWS 서비스를 이용을 위한 자격 증명 객체이다. properties파일에 설정된 accessKey와 secretKey를 이용하여 AWS 인증을 할 수 있게 해 준다.

S3와 상호작용하기 위한 클라이언트로 AmazonS3 Client를 사용한다.

@Component
@RequiredArgsConstructor
public class S3Utils {

    @Value("${aws.s3.bucket}")
    private String bucket;

    private final AmazonS3Client amazonS3Client;

    public String uploadFile(MultipartFile file) {
        try{
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());

            // 파일명 중복을 피하기 위한 파일이름 변환
            String filename = UUID.randomUUID() + "." + getExtension(Objects.requireNonNull(file.getOriginalFilename()));

            //업로드 요청
            amazonS3Client.putObject(bucket,filename,file.getInputStream(),metadata);

            return filename;
        } catch(IOException e){
            throw new CustomException(HttpStatus.CONFLICT,"파일 업로드에 실패했습니다,");
        }

    }

    public String getFileURL(String filename){
        return "https://버킷 이름.s3.ap-northeast-2.amazonaws.com"  + "/" + filename;
    }

    private String getExtension(String originalFilename){
        int idx = originalFilename.lastIndexOf('.');
        return originalFilename.substring(idx+1);
    }
}

파일 업로드, 파일 다운로드를 위한 메서드 등이 작성되어 있다.

컨트롤러에서 넘겨받은 Multipartfile의 콘텐츠 타입과 콘텐츠 길이를 ObjectMetadata에 담아준다.

그리고 혹시 있을 파일명의 중복을 피하기 위해 파일명을 변환해 준 다음 업로드를 요청한다.

파일의 다운로드는 변환된 파일이름과 버킷의 주소를 통해 가능하다.

'개발일지' 카테고리의 다른 글

20240103 - 심화프로젝트 KPT 회고  (0) 2024.01.03
20240101 - @Transactional  (0) 2024.01.02
20231227 - 예외처리  (0) 2023.12.27
20231226 - 다대다 관계와 중간테이블  (0) 2023.12.26
20231226 - 프로그래머스/140108  (0) 2023.12.26