s3 설정
application.yml
cloud:
aws:
s3:
bucket: bucketname
region:
static: ap-northeast-2
stack:
auto: false
credentials:
access-key: accessKey
secret-key: secretKey
S3Buckets.java
@Configuration
@ConfigurationProperties(prefix = "aws.s3.buckets")
public class S3Buckets {
private String airbnb;
public String getAirbnb() {
return airbnb;
}
public void setAirbnb(String airbnb) {
this.airbnb = airbnb;
}
}
@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(){
S3Client client = S3Client.builder()
.region(Region.AP_NORTHEAST_2)
.build();
return client;
}
@Bean
public AmazonS3Client amazonS3Client(){
BasicAWSCredentials basicAWSCredentials = new BasicAWSCredentials(accessKey, secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials))
.withRegion(region)
.build();
}
@Service
@RequiredArgsConstructor
public class S3Service {
private final S3Client s3Client;
public void putObject(String bucketName,String key, byte[] file){
PutObjectRequest objectRequest = PutObjectRequest.builder()
.bucket(bucketName)
.key(key)
.build();
s3Client.putObject(objectRequest, RequestBody.fromBytes(file));
}
이미지 저장
저장 경로는 버킷네임 / listing-image / 유저아이디 / UUID_filename 로 설정하였습니다
public Set<String> saveListingImage(List<MultipartFile> files,Integer account_id) {
Set<String> fileNameList = new HashSet<>();
files.forEach(file -> {
try {
String profileImageId = UUID.randomUUID().toString()+"_"+file.getOriginalFilename();
s3Service.putObject(s3Buckets.getAirbnb(),
"listing-images/%s/listing/%s".formatted(account_id,profileImageId),
file.getBytes());
fileNameList.add(profileImageId);
} catch (IOException e) {
throw new RuntimeException(e);
}
});
return fileNameList;
}
이미지 url 불러오기
public List<String> getListingImages(Integer listing_id, Integer account_id) {
Listing listing = listingRepository.findListingWithImagesById(listing_id).orElseThrow();
List<String> fileNameList = new ArrayList<>();
listing.getImages().stream().map(image->{
String url = amazonS3Client.getUrl(s3Buckets.getAirbnb(),
"listing-images/%s/listing/%s".formatted(account_id,image)).toString();
return fileNameList.add(url);
});
return fileNameList;
aws s3