소셜 로그인해서 프로필 사진을 s3에 업로드 하거나 이미지를 수정해서 s3에 올려야 하는 경우가 있었다.
s3Manager를 만들어서 모듈화 했다.
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@RequiredArgsConstructor
@Component
public class S3Manager {
private final AmazonS3Client amazonS3Client;
@Value("${cloud.aws.s3.bucket}")
private String bucket;
public String upload(MultipartFile multipartFile, String fileName) throws IOException {
File uploadFile = convert(multipartFile)
.orElseThrow(() -> new IllegalArgumentException("MultipartFile -> File로 전환이 실패했습니다."));
return upload(uploadFile, fileName);
}
public String upload(File uploadFile, String fileName) {
String uploadImageUrl = putS3(uploadFile, fileName);
removeNewFile(uploadFile);
return uploadImageUrl;
}
private String putS3(File uploadFile, String fileName) {
amazonS3Client.putObject(new PutObjectRequest(bucket, fileName, uploadFile).withCannedAcl(CannedAccessControlList.PublicRead));
return amazonS3Client.getUrl(bucket, fileName).toString();
}
private void removeNewFile(File targetFile) {
if (targetFile.delete()) {
log.info("파일이 삭제되었습니다.");
} else {
log.info("파일이 삭제되지 못했습니다.");
}
}
private Optional<File> convert(MultipartFile file) throws IOException {
File convertFile = new File(file.getOriginalFilename());
System.out.println("convertFile = " + convertFile);
if(convertFile.createNewFile()) {
try (FileOutputStream fos = new FileOutputStream(convertFile)) {
fos.write(file.getBytes());
}
return Optional.of(convertFile);
}
return Optional.empty();
}
public File downloadImage(String imageUrl,String fileName) {
URL url;
//읽기 객체
InputStream is;
//쓰기 객체
OutputStream os;
try {
url = new URL(imageUrl);
is = url.openStream();
os = new FileOutputStream(fileName);
byte[] buffer = new byte[1024*16];
while (true) {
int inputData = is.read(buffer);
if(inputData == -1)break;
os.write(buffer,0,inputData);
}
is.close();
os.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return new File(fileName);
}
}
application.properties
# AWS Account Credentials (AWS 접근 키)
cloud.aws.credentials.access-key='' //a키
cloud.aws.credentials.secret-key='' //s키
# AWS S3 bucket Info (S3 버킷정보)
cloud.aws.s3.bucket='' // 버킷이름
cloud.aws.region.static=ap-northeast-2
cloud.aws.stack.auto=false
gradle
implementation 'org.springframework.cloud:spring-cloud-starter-aws-secrets-manager-config:2.2.6.RELEASE'
'개발 > Spring' 카테고리의 다른 글
Spring @RequestParam @RequestBody @ModelAttribute 차이 (0) | 2022.03.20 |
---|---|
Part.1 Spring boot 갯수 제한 이벤트 구현(Redis 이용) Redisson, Transaction, Sync(lock) 유저가 많이 몰릴때. (0) | 2022.03.19 |
Spring boot NHN Cloud api-alimtalk 2.2 사용하기 (0) | 2022.03.19 |
Spring boot CORS 처리 (0) | 2022.03.17 |
Spring boot,nuxt(vue) oauth2 security token기반 소셜 로그인(카카오,네이버,구글,페이스북,로컬) (0) | 2022.03.13 |