๋ณด์ ์ทจ์ฝ์ ํด๊ฒฐ์ ์ํ AWS S3 ๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ณ๊ฒฝ
๊ฐ์
ํ๋ก์ ํธ ๋น๋ ์, ์ง์์ ์ผ๋ก ๋ฐ์ํ๋ ๊ฒฝ๊ณ ๋ฉ์์ง์ ์์ธ์ ํ์ธํ ๊ฒฐ๊ณผ, ๊ธฐ์กด์ ์ฌ์ฉํ๋ org.springframework.cloud:spring-cloud-starter-aws ๋ผ์ด๋ธ๋ฌ๋ฆฌ๊ฐ ๋ณด์ ์ทจ์ฝ์ ์ผ๋ก ์ธํด 2021๋
2์ ์ดํ Maven Repository์์ ๋ ์ด์ ์
๋ฐ์ดํธ๋ฅผ ์ง์์ ํ์ง ์๋๋ค๋ ์ฌ์ค์ ์๊ฒ ๋์์ต๋๋ค.
build.gradle์์๋ ์๋์ ๊ฐ์ด ์์กด์ฑ์ ์ทจ์ฝ์ ์ด ์๋ค๋ ๊ฒฝ๊ณ ๋ฉ์์ง๊ฐ ๋ํ๋ฉ๋๋ค.

ํด๊ฒฐ ๋ฐฉ๋ฒ
๋ผ์ด๋ธ๋ฌ๋ฆฌ ๋ณ๊ฒฝ
ํด๋น ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ๊ธฐ ์ํด org.springframework.cloud:spring-cloud-starter-aws ๋์ io.awspring.cloud:spring-cloud-aws-starter-s3:3.0.0 ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ก ๋ณ๊ฒฝํ์ต๋๋ค.
implementation 'io.awspring.cloud:spring-cloud-aws-starter-s3:3.0.0'
- ์ค์ ํ์ผ(S3Config.java) ์ญ์
Spring Cloud AWS S3๋ AWS์์ ์ ๊ณตํ๋ Java SDK์ ๋ฌ๋ฆฌ, ๋ณ๋์ ์ค์ ํ์ผ์ ์์ฑํ์ง ์์๋ ๋ฉ๋๋ค. CredentialsProviderAutoConfiguration ํด๋์ค๊ฐ application.yml์ ๋ฑ๋ก๋ access-key์ secret-key๋ฅผ ์๋์ผ๋ก ์ฝ์ด Credential ๊ด๋ จ Provider ๊ฐ์ฒด๋ค์ ์์ฑํฉ๋๋ค. ์ด๋ฅผ ํตํด AWS ์๋น์ค์ ์ ๊ทผํ ์ ์์ต๋๋ค.
(์ด ๊ณผ์ ์ ๋ด๋ถ์ ์ผ๋ก software.amazon.awssdk.services.s3 ๋ผ์ด๋ธ๋ฌ๋ฆฌ๋ฅผ ์ฌ์ฉํ์ฌ ๊ตฌํ๋ฉ๋๋ค.)
- application.yml ์ค์
๊ธฐ์กด ์ค์ ์์ spring ๋ค์์คํ์ด์ค๋ฅผ ์ถ๊ฐํด ์ค๋๋ค.
spring:
cloud:
aws:
s3:
bucket: ${bucket}
credentials:
access-key: ${accessKey}
secret-key: ${secretKey}
region:
static: ${awsRegion}
auto: false
stack:
auto: false
์ฝ๋ ์์
AmazonS3 ๋์ S3Template์ ์ฌ์ฉํ๋๋ก ์์ ํ์ต๋๋ค.
private final S3Template s3Template;
@Value("${spring.cloud.aws.s3.bucket}")
private String bucket;
public String saveFile(MultipartFile multipartFile) {
String originalFilename = multipartFile.getOriginalFilename();
String fileName = generateFileName(Objects.requireNonNull(originalFilename));
String imageUrl;
try {
S3Resource s3Resource = s3Template.upload(
bucket,
fileName,
multipartFile.getInputStream(),
ObjectMetadata.builder()
.contentType(multipartFile.getContentType())
.build()
);
imageUrl = s3Resource.getURL().toString();
} catch (IOException e) {
throw new ApiException(FILE_READ_FAILED);
}
return imageUrl;
}
private String generateFileName(String originalFilename) {
return UUID.randomUUID() + "-" + originalFilename.replace(" ", "_");
}
public void deleteFile(String fileUrl) {
try {
URL url = new URL(fileUrl);
String path = url.getPath();
String key = path.substring(1);
String decodedKey = URLDecoder.decode(key, StandardCharsets.UTF_8); // ํ๊ธ ๋๋ ํน์๋ฌธ์๊ฐ ์๋ ๊ฒฝ์ฐ๋ฅผ ์ํด
s3Template.deleteObject(bucket, decodedKey);
} catch (MalformedURLException e) {
throw new ApiException(INVALID_FILE_URL_FORMAT);
}
}
์ฐธ๊ณ ์๋ฃ
https://hinweis.tistory.com/111