스프링환경에서 S3에 파일을 업로드하기 위해서는 크게 credentials과 bucket 등의 정보를 담을 yml파일과 yml정보를 통해 환경변수 설정을 할 S3Config 마지막으로S이들을 이용해서 실제로 S3에 파일을 올릴 로직을 담을 S3Service가 필요하다.
- credentials정보가 외부에 노출되면 안되므로 application.yml에 아래와 같이 따로 파일을 빼준다
---
spring:
profiles.include:
- s3
이후 application.yml파일과 동일한 위치에 application-s3.yml을 생성해준다
필요한 내용들은 아래와 같고 발급받은 정보들을 입력해준다.
cloud:
aws:
credentials:
accessKey: 발급받은 accessKey
secretKey: 발급받은 secretKey
s3:
bucket: 버킷네임
region:
static: region명
다음으로 위의 정보들을 설정하기 위해 S3config를 만들어준다.
@Configuration
@RequiredArgsConstructor
public class S3Config {
@Value("${cloud.aws.s3.bucket}")
private String bucketName;
@Value("${cloud.aws.credentials.accessKey}")
private String accessKey;
@Value("${cloud.aws.credentials.secretKey}")
private String secretKey;
@Value("${cloud.aws.region.static}")
private String region;
@Bean
public AmazonS3 amazonS3(){
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
return AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(region)
.build();
}
}
다음은 실제로 파일을 올리게될 로직들이 들어간 S3Service이다.
선택한 파일을 지정된 버킷에 올린 후 해당 오브젝트에 대한 url을 리턴한다.
@Slf4j
@Service
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class S3Service {
private final AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
@Transactional
public String uploadFile(MultipartFile file){
String fileName = createFileName(file.getOriginalFilename());
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
String filePath;
// 파일 업로드
try (InputStream inputStream = file.getInputStream()) {
amazonS3.putObject(new PutObjectRequest(bucket, fileName, inputStream, objectMetadata)
.withCannedAcl(CannedAccessControlList.PublicRead));
// 올린 오브젝트에 대한 s3 url
filePath = amazonS3.getUrl(bucket, fileName).toString();
} catch (IOException e) {
throw new IllegalArgumentException("파일 업땅");
}
return filePath;
}
private String createFileName(String fileName) {
return UUID.randomUUID().toString().concat(getFileExtension(fileName));
}
private String getFileExtension(String fileName) {
log.info("fileName : {}", fileName.substring(fileName.lastIndexOf(".")));
return fileName.substring(fileName.lastIndexOf("."));
}
}
반응형
반응형
'⌨Programming > Spring' 카테고리의 다른 글
JPA 복합키 삭제 에러, 이슈 (0) | 2023.06.07 |
---|---|
Springboot 개발환경에서 노출되면 안되는 설정값, 환경변수 관리하기 (0) | 2023.05.12 |