요구사항
AWS S3 다른 버킷으로 업로드, 다운로드, 삭제 기능 구현
그냥 두개을 버킷을 사용하려면 두개의 빈을 생성하면 된다~~!
코드는 A 버킷, B 버킷으로 작성했다
Bean 등록
A, B 버킷 두가지를 빈으로 등록하는 과정
properties에 입력된 값을 읽어온다.
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Slf4j
@Configuration
public class S3Config {
@Value("${cloud.aws.credentials.a.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.a.secret-key}")
private String secretKey;
@Value("${cloud.aws.credentials.b.access-key}")
private String bAccessKey;
@Value("${cloud.aws.credentials.b.secret-key}")
private String bSecretKey;
@Value("${cloud.aws.region.static}")
private String region;
/**
* a S3 bucket
* @return
*/
@Bean(name = "amazonS3")
public AmazonS3 amazonS3() {
AmazonS3 s3Builder = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKey, secretKey)))
.build();
return s3Builder;
}
/**
* b S3 bucket
* @return
*/
@Bean(name = "amazonS3b")
public AmazonS3 amazonS3b() {
AmazonS3 s3Builder = AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(bAccessKey, bSecretKey)))
.build();
return s3Builder;
}
}
Interface 생성, Service 생성
Interface
public interface UploadService {
void uploadFile(InputStream inputStream, ObjectMetadata objectMetadata, String fileName);
ResponseEntity<byte[]> downloadFile(Attach attach) throws IOException;
void deleteFile(String filePath);
String getFileUrl(String fileName);
}
Service
@Component 어노테이션 사용, lombok - @RequiredArgsConstructor 사용하여 Bean 생성자 주입 처리
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.*;
import kr.aaa.bbb.model.entity.common.Attach;
import kr.aaa.bbb.config.aws.S3Config;
import kr.aaa.bbb.util.FileUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
@RequiredArgsConstructor
@Component
@Slf4j
public class UploadS3Service implements UploadService{
@Qualifier("amazonS3")
private final AmazonS3 amazonS3;
@Qualifier("amazonS3b")
private final AmazonS3 amazonS3b;
@Value("${aws.s3.a.bucket}")
private String bucket;
@Value("${aws.s3.b.bucket}")
private String bBucket;
private final S3Config s3Config;
private final String BASE_URL = "https://a.aaaa.co.kr.s3.ap-northeast-2.amazonaws.com/";
@Override
public void uploadFile(InputStream inputStream, ObjectMetadata objectMetadata, String fileName) {
amazonS3.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata).withCannedAcl(CannedAccessControlList.Private)
);
}
@Override
public ResponseEntity<byte[]> downloadFile(Attach attach) throws IOException {
/**
* https://a.aaa.co.kr.s3.ap-northeast-2.amazonaws.com/a/file/2022/01/12/fdwfdx-3353-322-82c7-930503a62d1bdwscs.jpg
* 아래의 형태로 가공 (key 값 추출)
* a/file/2022/01/12/fdwfdx-3353-322-82c7-930503a62d1bdwscs.jpg
*/
String filePath = StringUtils.removeIgnoreCase(attach.getFilePath(), BASE_URL);
S3Object o = amazonS3.getObject(new GetObjectRequest(bucket, filePath));
S3ObjectInputStream objectInputStream = o.getObjectContent();
byte[] bytes = IOUtils.toByteArray(objectInputStream);
/**
* 다운로드 명 설정(난수화 된 이름 말고, original 이름으로 다운로드 처리)
*/
String downloadFileName = URLEncoder.encode(attach.getOriginFileName(), "UTF-8").replaceAll("\\+", "%20");
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.setContentType(FileUtil.getMediaType(attach.getAttachFileName()));
httpHeaders.setContentLength(bytes.length);
httpHeaders.setContentDispositionFormData("attachment", downloadFileName);
return new ResponseEntity<>(bytes, httpHeaders, HttpStatus.OK);
}
@Override
public void deleteFile(String filePath) {
boolean isExistObject = amazonS3.doesObjectExist(bucket, filePath);
if (isExistObject == true) {
amazonS3.deleteObject(bucket, filePath);
}
}
@Override
public String getFileUrl(String fileName) {
return amazonS3.getUrl(bucket, fileName).toString();
}
public void bUploadFile(InputStream inputStream, ObjectMetadata objectMetadata, String fileName) {
amazonS3b.putObject(new PutObjectRequest(bBucket, fileName, inputStream, objectMetadata).withCannedAcl(CannedAccessControlList.PublicRead)
);
}
public String bGetFileUrl(String fileName) {
return amazonS3b.getUrl(bBucket, fileName).toString();
}
}
Pom.xml
깜박하고 올리지 않아서 수정...! 아래와 같은 라이브러리를 사용했당
import 부분도 추가..! 블로그 서칭하다보면 잘 안되는 경우가 있는데 import를 보면 왜 안되는지 힌트가 있을 수도 있당
apache common 라이브러리도 같이 사용했던 것 같다
<!-- AWS S3 라이브러리 -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>