티스토리 뷰

오늘은 Spring boot를 이용하여 AWS S3 버킷에 이미지를 업로드 코드를 리뷰하겠다.

본격적으로 코드에 들어가기 앞서, 기본적으로 설정해야 하는 것들이 있다.

 

1. S3 버킷 생성

2. IAM 사용자 추가 및 accesskey, secretkey 발급

 

위의 사항들을 모두 하였으면 바로 코드로 들어가겠다.

우선 Dependency부터 추가하겠다.(gradle)

 

package com.project.cooksistant.s3;

import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CannedAccessControlList;
import com.amazonaws.services.s3.model.PutObjectRequest;
import lombok.NoArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.IOException;

@NoArgsConstructor
@Service
public class S3Uploader {
    private AmazonS3 s3Client;

    @Value("${cloud.aws.credentials.accessKey}")
    private String accessKey;
    @Value("${cloud.aws.credentials.secretKey}")
    private String secretKey;

    @Value("${cloud.aws.s3.bucket}")
    private String bucket;

    @Value("${cloud.aws.region.static}")
    private String region;

    @PostConstruct
    public void setS3Client() {
        AWSCredentials credentials = new BasicAWSCredentials(this.accessKey, this.secretKey);

        s3Client = AmazonS3ClientBuilder.standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(this.region)
                .build();
    }

    public String upload(MultipartFile file, Long recipeId) throws IOException {
        String fileName = "pic_" + recipeId + ".jpg";
        System.out.println(fileName);
        s3Client.putObject(new PutObjectRequest(bucket, fileName, file.getInputStream(), null)
                .withCannedAcl(CannedAccessControlList.PublicRead));
        return s3Client.getUrl(bucket, fileName).toString();
    }

    public String uploadStep(MultipartFile file, Long stepId) throws IOException {
        String fileName = "pic_" + stepId + ".jpg";
        System.out.println(fileName);
        s3Client.putObject(new PutObjectRequest(bucket+"/step", fileName, file.getInputStream(), null)
                .withCannedAcl(CannedAccessControlList.PublicRead));
        return s3Client.getUrl(bucket+"/step", fileName).toString();
    }
}

 

upload와 uploadStep 이렇게 두 개가 있는데, 현재 프로젝트를 진행하면서 서로 다른 테이블에 이미지 url을 저장해야 하므로 2개를 구현하였다.

 

@ApiOperation(value = "레시피 메인 사진 S3업로드 및 컬럼 값 설정", notes = "Request\n" +
            "                                                   - file: 사진\n" +
            "                                                   - recipeId: 레시피 인덱스")
    @PostMapping(value = "/recipe/mainImage")
    public void mainImage(@RequestParam("file") MultipartFile file, @RequestParam("recipeId") Long recipeId) throws IOException {
        recipeService.mainImage(file, recipeId);
    }

 

Controller에 s3Uploader를 호출하는 코드이다. recipeId에 해당하는 행을 찾고 해당 행의 칼럼 값의 이미지 url부분에 s3 이미지 url값으로 넣는다.

공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/02   »
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
글 보관함