🥺 이전 포스팅에서 AWS S3 버킷과 IAM 사용자 생성을 마쳤다
https://dev-tanda.tistory.com/16
AWS S3 이미지 업로드 - 1 (S3, IAM 생성)
🤔 스프링부트 프로젝트 중 로컬에 업로드 중이던 이미지를 AWS S3에 업로드 하려고 한다 먼저 AWS S3 버킷과 IAM 사용자를 생성해둬야 한다 1. AWS S3 버킷만들기 - AWS S3에 들어가서 [버킷만들기] 버
dev-tanda.tistory.com
SpringBoot에서 구현해보자 (ver 2.7.18)
1. pom.xml
- dependency 추가 (Maven)
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.2.6.RELEASE</version>
</dependency>
2. application.yml
- aws cloud 설정 추가
cloud:
aws:
s3:
bucketname: 버킷명
credentials:
access-key: 액세스키
secret-key: 비밀 액세스키
region:
static: ap-northeast-2
auto: false
stack:
auto: false
※ 액세스키는 절대 유출되지 않도록 한다, 그냥 gitHub에 커밋했다가 아주 번거로워질 수 있다
3. S3Config.java
- 새로운 S3Config 클래스 추가
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
@Configuration
public class S3Config {
@Value("cloud.aws.credentials.accessKey")
private String accessKey;
@Value("cloud.aws.credentials.secretKey")
private String secretKey;
@Value("cloud.aws.s3.bucketName")
private String bucketName;
@Value("cloud.aws.region.static")
private String region;
@Bean
public AmazonS3 s3Builder() {
AWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey);
return AmazonS3ClientBuilder.standard()
.withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
.withRegion(region).build();
}
}
4. Service
a) 업로드, URL 반환
- S3 버킷에 이미지를 업로드하고, URL을 반환받는 메서드
@Service
@RequiredArgsConstructor
public class MyService {
// AmazonS3 멤버변수 선언
private final AmazonS3 amazonS3;
// application.yml 내의 버킷이름 가져오기
@Value("${cloud.aws.s3.bucketname}")
private String bucketName;
// 이미지 이름 중복 방지를 위해 UUID 사용
private String changedImageName(String originName) {
String random = UUID.randomUUID().toString();
return random + originName.substring(originName.lastIndexOf("."));
}
// 이미지를 S3에 업로드 후, URL 반환
private String uploadImageToS3(MultipartFile file) {
String originName = file.getOriginalFilename();
String changedName = changedImageName(originName);
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentType(file.getContentType());
metadata.setContentLength(file.getSize());
try {
amazonS3.putObject(new PutObjectRequest(bucketName, changedName, file.getInputStream(), metadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
} catch (IOException e) {
throw new IllegalArgumentException("이미지 업로드 중 오류 발생", e);
}
return amazonS3.getUrl(bucketName, changedName).toString();
}
}
- 다음과 같이 이미지의 이름, 경로를 사용하면 된다
String imgName = file.getOriginalFilename();
String imgPath = uploadImageToS3(file);
- 메서드 구현 후 이미지 업로드를 진행하면 비킷에 이미지가 업로드 되는 것을 확인 할 수 있을 것이다
- 업로드된 이미지 정보의 객체 URL로 접속하면 이미지가 나올 것이다
b) 수정 시 삭제
- 이미지 수정 시 원본을 삭제하는 메서드
- 공식문서를 보면 삭제 시 버킷명과 객체키가 필요하다, 여기서 객체 키는 객체 URL의 amazonaws.com/ 뒷부분이다
- 객체URL >> String imgPath = uploadImageToS3(file);
// 이미지 수정시 S3 이미지 삭제
public void deleteImage(String imgPath) {
String splitStr = "amazonaws.com/";
String key = imgPath.substring(imgPath.lastIndexOf(splitStr) + splitStr.length());
DeleteObjectRequest deleteRequest = new DeleteObjectRequest(bucketName, key);
amazonS3.deleteObject(deleteRequest);
}
- 나는 이미지 등록으로 사용하는 메서드 내에 다음과 같은 조건을 추가해서 삭제를 진행했다
if (user.getImgPath() != null) {
deleteImage(persistence.getImgPath());
}
'개발 > AWS' 카테고리의 다른 글
[AWS S3] 이미지 업로드 - 1 (S3, IAM 생성) (0) | 2024.02.12 |
---|