
Simple Storage Service์ ์ฝ์๋ก, ์ฃผ๋ก ํ์ผ ์๋ฒ๋ก ์ฌ์ฉํ๋ค.
ํ์ผ ์๋ฒ๋ ํธ๋ํฝ ์ฆ๊ฐ์ ๋ฐ๋ผ ์๋ฒ ์ธํ๋ผ ๋ฐ ์ฉ๋ ๊ณํ์ ๋ณ๊ฒฝํด์ผ ํ๋ค. ํ์ง๋ง S3๋ ํ์ฅ ๋ฐ ์ฑ๋ฅ ๋ถ๋ถ์ ๋์ ์ฒ๋ฆฌํด์ฃผ๊ธฐ ๋๋ฌธ์ ๋ ํธ๋ฆฌํ๊ฒ ์ฌ์ฉํ ์ ์๋ค.
S3๋ ์ฌ๋ฌ ์์ญ์์ ์ฌ๋ฌ ๋ฐ์ดํฐ ๋ณต์ฌ๋ณธ์ ์ ์ฅํ๊ธฐ ๋๋ฌธ์ ํ ์์ญ์ด ๋ค์ด๋๋๋ผ๋ ๋ฐ์ดํฐ ์ฌ์ฉ ๋ฐ ๋ณต๊ตฌ๊ฐ ๊ฐ๋ฅํ๋ค.



S3์ ์ ๊ทผํ๊ธฐ ์ํด์๋ IAM ์ฌ์ฉ์์๊ฒ S3 ์ ๊ทผ ๊ถํ์ ์ฃผ๊ณ , ์์ธ์ค ํค๋ฅผ ๋ง๋ค์ด ์์ธ์ค ํค์ ๋น๋ฐ ํค๋ฅผ ํตํด ์ ๊ทผํด์ผ ํ๋ค. ์ด๋ฏธ IAM ์ฌ์ฉ์๋ก ๋ก๊ทธ์ธํด ์๋ ๊ฒฝ์ฐ์๋ ์์ฑํ๋ ๊ณผ์ ์ ์๋ต ํ ๋ฐ๋ก ์ค์ ํ๋ฉด ๋๋ค.


AmazonS3FullAccess๋ฅผ ์ ํํ๋ค.

์ธ๋ถ ์๋ฒ์์ ์ ์ํ ์ ์๋๋ก IAM ์ฌ์ฉ์์ ์์ธ์ค ํค๋ฅผ ์์ฑํด์ผ ํ๋ค. ์ด๋ ์์ธ์ค ํค์ ๋น๋ฐ ํค๋ ์ธ๋ถ์ ๊ณต๊ฐ๋์ด์๋ ์๋๋ค.



์์ฑ ์๋ฃ ํ๋ฉด์ด ์๋๋ฉด ๋น๋ฐํค๋ฅผ ๋ณผ ์ ์๊ธฐ ๋๋ฌธ์ ๋ฐ๋์
.csvํ์ผ๋ก ๋ฐ์๋์ ๊ฒ์ ๊ถ์ฅํ๋ค.

dependencies {
...
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
...
}
cloud:
aws:
s3:
bucket: <S3 bucket name>
stack:
auto: false
region:
static: ap-northeast-2
auto: false
credentials:
accessKey: <๋ฐ๊ธ๋ฐ์ accessKey>
secretKey: <๋ฐ๊ธ๋ฐ์ secretKey>
@Configuration
public class S3Config {
@Value("${cloud.aws.credentials.access-key}")
private String accessKey;
@Value("${cloud.aws.credentials.secret-key}")
private String secretKey;
@Value("${cloud.aws.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();
}
}
@Service
@RequiredArgsConstructor
public class S3UploadService {
private final AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
public String saveFile(MultipartFile multipartFile) throws IOException {
String originalFilename = multipartFile.getOriginalFilename();
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(multipartFile.getSize());
metadata.setContentType(multipartFile.getContentType());
amazonS3.putObject(bucket, originalFilename, multipartFile.getInputStream(), metadata);
return amazonS3.getUrl(bucket, originalFilename).toString();
}
}
public ResponseEntity<UrlResource> downloadImage(String originalFilename) {
UrlResource urlResource = new UrlResource(amazonS3.getUrl(bucket, originalFilename));
String contentDisposition = "attachment; filename=\"" + originalFilename + "\"";
// header์ CONTENT_DISPOSITION ์ค์ ์ ํตํด ํด๋ฆญ ์ ๋ค์ด๋ก๋ ์งํ
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.body(urlResource);
}
public void deleteImage(String originalFilename) {
amazonS3.deleteObject(bucket, originalFilename);
}
Reference : [Spring Boot] AWS S3๋ฅผ ์ด์ฉํ ํ์ผ ์ ๋ก๋, AWS S3 ๊ณต์ ๋ฌธ์