개발일기
SpringBoot AWS 설정하는 방법 본문
🔥 BuildGradle - 의존성 추가
// aws-bucket
implementation 'io.awspring.cloud:spring-cloud-starter-aws:2.4.4'
// 파일 업로드
implementation 'commons-io:commons-io:2.14.0'
implementation 'commons-fileupload:commons-fileupload:1.5'
🛠️ application.yml - aws 자격 증명 입력
cloud:
aws:
credentials:
instance-profile: false
accessKey: ${LOC_AWS_ACCESS_KEY}
secretKey: ${LOC_AWS_SECRET_KEY}
s3:
bucket: ${LOC_AWS_BUCKET_NAME}
region:
auto: false
static: ap-northeast-2
stack: false
🤗 Bean 등록
package darkoverload.itzip.global.config.aws;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* S3 연결을 위한 Bean 등록
*/
@Configuration
public class AWSS3Config {
@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 AmazonS3Client amazonS3Client() {
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
return (AmazonS3Client) AmazonS3ClientBuilder
.standard()
.withCredentials(new AWSStaticCredentialsProvider(credentials))
.withRegion(region)
.build();
}
}
🔥 AWSService.class
package darkoverload.itzip.infra.bucket.aws;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.ObjectMetadata;
import darkoverload.itzip.image.domain.image;
import darkoverload.itzip.image.exception.CustomFileException;
import darkoverload.itzip.global.config.response.code.CommonExceptionCode;
import darkoverload.itzip.global.util.FileUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import java.io.IOException;
import java.io.InputStream;
@Component
@RequiredArgsConstructor
public class AWSService {
private final AmazonS3Client amazonS3;
@Value("${cloud.s3.s3.bucket}")
private String bucketName;
@Value("${file.path}")
private String filePath;
public image upload(image image, InputStream inputStream) {
String fileName = FileUtil.generateFileName(image.getFilename());
amazonS3.putObject(bucketName, fileName, inputStream, getObjectMetadata(image));
image in = null;
try {
String dirUrl = filePath + fileName;
in = image.builder()
.filePath(dirUrl)
.filename(fileName)
.size(image.getSize())
.fileType(FileUtil.getMimeType(inputStream))
.contentType(image.getContentType())
.build();
} catch (IOException e) {
throw new CustomFileException(CommonExceptionCode.FILE_ERROR);
}
return in;
}
private ObjectMetadata getObjectMetadata(image image) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentType(image.getContentType());
objectMetadata.setContentLength(image.getSize());
return objectMetadata;
}
}
아래 코드에서 fileName 을 만들어주었다. FileUtil에 있는 generateFileName을 통해서 파일 이름을 UUID로 스트링으로 바꿔서 내려줬다.
amazonS3.putObject를 통해서 bucket을 실질적으로 이미지를 업로드 해주었다.
String fileName = FileUtil.generateFileName(image.getFilename());
amazonS3.putObject(bucketName, fileName, inputStream, getObjectMetadata(image));
아래 코드는 dirUrl 같은 경우에는 cloudfront에 해당하는 https url로 이미지를 가져오기 위하여 설정해주었다.
image in = null;
try {
String dirUrl = filePath + fileName;
in = image.builder()
.filePath(dirUrl)
.filename(fileName)
.size(image.getSize())
.fileType(FileUtil.getMimeType(inputStream))
.contentType(image.getContentType())
build();
} catch (IOException e) {
throw new CustomFileException(CommonExceptionCode.FILE_ERROR);
}
}
'취준생 프로젝트' 카테고리의 다른 글
WebClient를 사용한 커리어넷 학교 정보 API가져오기 (0) | 2024.08.08 |
---|---|
Sping boot AWS bucket 업로드, 수정 , 삭제하기 (4) | 2024.07.23 |
AWS CloudFront 를 통한 안전한 S3 버킷 정책 설정 (1) | 2024.07.14 |
취준생 프로젝트 ERD 구조 및 회고 (0) | 2024.06.27 |
취준생 프로젝트 use-flow 및 요구사작성하기 (0) | 2024.06.22 |