✅ 개요
해당 포스트에서 기본적인 S3 설정을 해주었다.
이제 해당 S3 버킷과 스프링부트를 연동시켜 이미지를 업로드해보겠다.
✅ AWS 의존성 추가
1️⃣ Spring Cloud AWS Starter
implementation 'io.awspring.cloud:spring-cloud-aws-starter:3.1.1'
https://mvnrepository.com/artifact/io.awspring.cloud/spring-cloud-aws-starter/3.1.1
- Spring Boot와 AWS의 통합을 도와주는 라이브러리이다.
2️⃣ AWS Java SDK For Amazon S3
implementation 'com.amazonaws:aws-java-sdk-s3:1.12.767'
https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3/1.12.767
- Java 어플리케이션에서 Amazon S3(Simple Storage Service) 버킷에 접근할 수 있게 해주는 라이브러리
- 해당 라이브러리는 aws sdk v1이며 이 라이브러리는 25년 12월 31일에 만료된다고 한다.
실제로 해당 의존성을 추가하고 어플리케이션을 실행하면 아래와 같은 로그가 나온다.
The AWS SDK for Java 1.x entered maintenance mode starting July 31, 2024 and will reach end of support on December 31, 2025. For more information, see <https://aws.amazon.com/blogs/developer/the-aws-sdk-for-java-1-x-is-in-maintenance-mode-effective-july-31-2024/>
You can print where on the file system the AWS SDK for Java 1.x core runtime is located by setting the AWS_JAVA_V1_PRINT_LOCATION environment variable or aws.java.v1.printLocation system property to 'true'.
This message can be disabled by setting the AWS_JAVA_V1_DISABLE_DEPRECATION_ANNOUNCEMENT environment variable or aws.java.v1.disableDeprecationAnnouncement system property to 'true'.
- 현재 aws sdk v2가 따로 존재하며 이는 더 좋은 성능을 제공한다. 하지만 해당 버전은 취약성이 존재해서 지금으로썬 aws sdk v1을 쓰다가 추후 취약성 문제가 해결되면 넘어가면 될듯 싶다. 해당 포스트에선 v1으로 진행하도록 하겠다.
- 참고로 v1과 v2의 문법이 꽤 다르다.
v2 관련 링크
https://mvnrepository.com/artifact/software.amazon.awssdk/s3
✅ S3 관련 설정정보 추가하기
Spring boot에서 S3에 접근하기 위해서는 설정파일에 몇가지 정보를 적어줘야 한다.
application.yml에 다음과 같은 부분을 추가했다.
cloud:
aws:
credentials:
access-key: <IAM에서 발급받은 액세스키>
secret-key: <IAM에서 발급받은 시크릿키>
region:
static: ap-northeast-2
s3:
bucket: <버킷이름>
발급은 해당 포스트에서 진행했었다.
✅ 이미지 업로드 테스트
1️⃣ S3Client 빈 등록
우선 S3Client의 설정정보를 입력해서 빈으로 등록해야 한다.
@Configuration
public class S3Config {
@Value("${spring.cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${spring.cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${spring.cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3 amazonS3() {
BasicAWSCredentials awsCreds = new BasicAWSCredentials(accessKey, secretKey);
return AmazonS3ClientBuilder.standard()
.withRegion(region)
.withCredentials(new AWSStaticCredentialsProvider(awsCreds))
.build();
}
}
2️⃣ Service 계층
S3 버킷에 이미지를 업로드 하는 코드를 구현해줬다.
@Service
public class S3Service {
private final AmazonS3 amazonS3;
@Value("${spring.cloud.aws.s3.bucket}")
private String bucket;
public S3Service(AmazonS3 amazonS3) {
this.amazonS3 = amazonS3;
}
/**
* S3에 이미지 업로드 하기
*/
public String uploadImage(MultipartFile image) throws IOException {
String fileName = UUID.randomUUID() + "_" + image.getOriginalFilename(); // 고유한 파일 이름 생성
// 메타데이터 설정
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(image.getContentType());
metadata.setContentLength(image.getSize());
// S3에 파일 업로드 요청 생성
PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, image.getInputStream(), metadata);
// S3에 파일 업로드
amazonS3.putObject(putObjectRequest);
return getPublicUrl(fileName);
}
private String getPublicUrl(String fileName) {
return String.format("https://%s.s3.%s.amazonaws.com/%s", bucket, amazonS3.getRegionName(), fileName);
}
- getPublicUrl()
- S3에 저장 후 해당 Url을 들어가면 그 이미지가 나온다.
- 나는 url을 데이터베이스에 저장하고 프론트에 넘겨줄 생각이라 url형식으로 변환해주는 메서드를 추가적으로 작성하였다.
- S3 객체의 url은 https://%s.s3.%s.amazonaws.com/%s과 같은 형식으로 저장된다.
3️⃣ Controller 계층
@RestController
@RequestMapping("/s3")
@RequiredArgsConstructor
public class S3TestController {
private final S3Service s3Service;
@PostMapping("/upload")
public String uploadFile(@RequestParam("file") MultipartFile file) {
try {
String imageUrl = s3Service.uploadImage(file);
return "File uploaded successfully! imageUrl: " + imageUrl;
} catch (Exception e) {
e.printStackTrace();
return "File upload failed!";
}
}
}
✅ Postman으로 Test
🏙️ 테스트할 이미지
📮 PostMan으로 API 요청
업로드가 잘 된걸 알 수 있다.
받아온 URL로 들어가보면 업로드한 이미지가 잘나온다.
✅ 마치며
백엔드 서버 기능 구현을 위한 모든 준비가 완료됐다. 이제 본격적으로 스프링부트에서 이미지를 업로드하고 수정하는 서버 로직을 구현해보겠다.
'AWS' 카테고리의 다른 글
[AWS 실습 프로젝트] 5. EC2에 스프링부트 백엔드 서버 배포하기 (0) | 2024.09.17 |
---|---|
[AWS 실습 프로젝트] 4. Spring boot로 S3에 이미지 업로드 및 수정 비즈니스 로직 구현하기 (0) | 2024.09.17 |
[AWS 실습 프로젝트] 2. 이미지 업로드를 위한 AWS S3 인프라 구성 (1) | 2024.09.17 |
[AWS 실습 프로젝트] 1. 프로젝트 개요 (0) | 2024.09.17 |
Amazon Ec2 인스턴스 생성하기 (0) | 2024.04.01 |