이번에는 S3에 파일 업로드하는 방법을 알아보겠습니다.
S3 파일 업로드
// 버킷 주소명
@Value("${cloud.aws.s3.bucket}")
private String bucket;
private final AmazonS3Client amazonS3Client;
// dirName = 사진 저장할 폴더명
public void upload(MultipartFile multipartFile, String dirName) throws IOException {
// 파일 정보 추가
ObjectMetadata objMeta = new ObjectMetadata();
objMeta.setContentType(multipartFile.getContentType());
objMeta.setContentLength(multipartFile.getSize());
String originalFilename = multipartFile.getOriginalFilename();
// 파일 저장
putS3(multipartFile, dirName+"/"+originalFilename, objMeta);
}
// 파일 저장
private void putS3(MultipartFile multipartFile, String fileName, ObjectMetadata objMeta) throws IOException{
amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, multipartFile.getInputStream(), objMeta)
.withCannedAcl(CannedAccessControlList.PublicRead));
return amazonS3Client.getUrl(bucket, fileName).toString();
}
S3 파일 삭제
// 이미지 s3에서 삭제
public void deleteImage(String url) {
amazonS3Client.deleteObject(bucket, url);
}