티스토리 뷰

반응형

클라이언트 요청으로 이미지를 받아 S3에 업로드하면, S3에서 반환해주는 이미지 url을 DB에 저장해 사용한다.

 

build.gradle에 의존성 추가하기

implementation("org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE")

 

application.properties에 액세스 키 등 등록하기

aws.credentials.access-key=
aws.credentials.secret-key=
aws.credentials.region=
aws.s3.bucket=

 

Config 등록하기

@Configuration
class S3Config (
    @Value("\${aws.credentials.access-key}") val accessKey: String,
    @Value("\${aws.credentials.secret-key}") val secretKey: String,
    @Value("\${aws.credentials.region}") val region: String,
){

    @Bean
    fun amazonS3Factory() = BasicAWSCredentials(accessKey, secretKey).let {
        AmazonS3ClientBuilder.standard()
            .withCredentials(AWSStaticCredentialsProvider(it))
            .withRegion(region)
            .build() as AmazonS3Client
    }
}

 

 

@Component
class S3ImageRepoImpl @Autowired constructor(
    private val s3Client: AmazonS3Client,
    @Value("\${aws.s3.bucket}") val bucket: String
): ImageRepo {

    override fun upload(image: MultipartFile, dir: String): String {
    	val file = File()
        image.transferTo(file)
        s3Client.putObject(PutObjectRequest(bucket, fileName, file).withCannedAcl(CannedAccessControlList.PublicRead))
        file.delete()
        return s3Client.getUrl(bucket, fileName).toString()
    } // inputstream 이용
    
    override fun upload(image: MultipartFile, dir: String): String {
    	val metaData = ObjectMetadata().apply {
            this.contentType = image.contentType
            this.contentLength = image.size
        }
        s3Client.putObject(PutObjectRequest(bucket, fileName, image.inputStream, metaData).withCannedAcl(CannedAccessControlList.PublicRead))
        return s3Client.getUrl(bucket, fileName).toString()
    } // File 이용
}

 

반응형
반응형
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
글 보관함