ํ๋กํ ์ฌ์ง, ๋ ์ํผ ์ฌ์ง, SNS ํผ๋ ์ฌ์ง ๋ฑ์ ์ ๋ก๋ ํ๊ธฐ ์ํด์ AWS S3๋ฅผ ์ฌ์ฉํ๋ ค๊ณ ํ๋ค.
Spring Cloud AWS์ ๋ฒ์ ์ค์
<properties>
<spring-cloud-aws.version>3.1.1</spring-cloud-aws.version>
</properties>
Spring Cloud AWS์ ์์กด์ฑ ๊ด๋ฆฌ
<dependencyManagement>
<dependencies>
<dependency>
<groupId>io.awspring.cloud</groupId>
<artifactId>spring-cloud-aws-dependencies</artifactId>
<version>${spring-cloud-aws.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
Amazon S3 SDK ์์กด์ฑ ์ถ๊ฐ
<dependencies>
<dependency>
<groupId>software.amazon.awssdk</groupId>
<artifactId>s3</artifactId>
<version>2.21.46</version>
</dependency>
</dependencies>
AWS S3 ์๋น์ค ์ค์
cloud.aws.s3.bucket=<S3 ๋ฒํท ์ด๋ฆ>
cloud.aws.region.auto=false // AWS ๋ฆฌ์ ์ ์๋์ผ๋ก ๊ฐ์งํ๋ ๊ธฐ๋ฅ ๋นํ์ฑํ
cloud.aws.stack.auto=false // AWS CloudFormation ์คํ์์ ๋ฆฌ์์ค๋ฅผ ์๋์ผ๋ก ๊ฐ์งํ๋ ๊ธฐ๋ฅ ๋นํ์ฑํ
cloud.aws.region.static=ap-northeast-2 // ์ฌ์ฉํ AWS ๋ฆฌ์ ์ ์ค์ (ap-northeast-2 : ์์ธ ๋ฆฌ์ )
cloud.aws.credentials.access-key= // AWS ๊ณ์ ์ access key ์ค์
cloud.aws.credentials.secret-key= // AWS ๊ณ์ ์ secret key ์ค์
spring.servlet.multipart.enabled=true // Spring์ Multipart ํ์ผ ์
๋ก๋ ๊ธฐ๋ฅ ํ์ฑํ
@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 S3Client s3Client(){
AwsBasicCredentials awsBasicCredentials = AwsBasicCredentials.create(accessKey, secretKey); // AWS ์๊ฒฉ ์ฆ๋ช
์์ฑ
return S3Client.builder() // S3 ํด๋ผ์ด์ธํธ ๊ตฌ์ฑ
.credentialsProvider(StaticCredentialsProvider.create(awsBasicCredentials)) // ์์ฑ๋ ์๊ฒฉ ์ฆ๋ช
์ ๊ณต
.region(Region.of(region)) // ์ค์ ๋ AWS ๋ฆฌ์ ์ ์ง์
.build(); // S3Client ์ธ์คํด์ค ์์ฑ
}
}
@Service
public class S3Service {
private final S3Client s3Client;
@Value("${cloud.aws.s3.bucket}")
private String bucketName;
@Autowired
public S3Service(S3Client s3Client) {
this.s3Client = s3Client;
}
// MultipartFile์ ๋ฐ์ S3์ ์
๋ก๋ํ๊ณ , ์
๋ก๋๋ ํ์ผ์ URL์ ๋ฐํ
public String uploadFile(MultipartFile file) {
String fileName = generateFileName(file);
try {
PutObjectRequest putObjectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(fileName)
.acl("public-read") // ํ์ผ์ ๊ณต๊ฐ์ ์ผ๋ก ์ฝ์ ์ ์๋๋ก ์ค์
.contentType(file.getContentType()) // ์
๋ก๋ํ๋ ํ์ผ์ ์ค์ MIME ํ์
์ ์ค์
.contentDisposition("inline") // ๋ธ๋ผ์ฐ์ ์์ ํ์ผ์ ์ง์ ํ์
.build();
s3Client.putObject(putObjectRequest, RequestBody.fromInputStream(file.getInputStream(), file.getSize()));
return String.format("https://%s.s3.amazonaws.com/%s", bucketName, fileName);
} catch (IOException e) {
throw new RuntimeException("ํ์ผ ์
๋ก๋์ ์คํจํ์ต๋๋ค", e);
}
}
// ํ์ผ ์ด๋ฆ ์์ฑ
private String generateFileName(MultipartFile file) {
return UUID.randomUUID().toString() + "-" + file.getOriginalFilename();
}
}
์ฐธ๊ณ ์๋ฃ
https://gaeggu.tistory.com/33
https://bigco-growth-diary.tistory.com/43