spring으로 이미지 업로드를 구현하던 도중 로컬 디렉토리가 아닌 S3에 이미지를 저장하게 할 수 있도록 만들고자 했다.
출처 : https://chb2005.tistory.com/200
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Statement1",
"Principal": "",
"Effect": "Allow",
"Action": "s3:",
"Resource": "arn:aws:s3:::<버킷 이름>/*"
}
]
}
implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
@Service
@RequiredArgsConstructor
public class PropertyImageService {
private final PropertyRepository propertyRepository;
private final PropertyImageRepository propertyImageRepository;
private final AmazonS3 amazonS3;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
public void uploadImage(Long propertyID, PropertyImageDto propertyImageDto) {
Property property = propertyRepository.findById(propertyID)
.orElseThrow(() -> new ApplicationException(ErrorCode.Property_NOT_FOUND, "없음"));
List<PropertyImage> propertyImages = propertyImageDto.getImages().stream()
.map(image -> new PropertyImage(property, saveImage(image)))
.collect(Collectors.toList());
propertyImageRepository.saveAll(propertyImages);
}
private String saveImage(MultipartFile image) {
String fileName = "image_" + UUID.randomUUID() + "." + getFileExtension(image.getOriginalFilename());
ObjectMetadata metadata = new ObjectMetadata();
metadata.setContentLength(image.getSize());
metadata.setContentType(image.getContentType());
try {
amazonS3.putObject(bucket, fileName, image.getInputStream(),metadata);
} catch (IOException e) {
e.printStackTrace();
throw new ApplicationException(ErrorCode.IMAGE_SAVE_ERROR, "이미지 저장 실패");
}
return amazonS3.getUrl(bucket,fileName).toString();
}
private String getFileExtension(String filename) {
return filename.substring(filename.lastIndexOf(".")+1);
}
}