AWS S3 활용하여 이미지 업로드하기 (Spring)

2023. 11. 2. 16:41
728x90

1. Bucket 생성

2. IAM 사용자 생성

3. 액세스 키 생성

4. 버킷 정책 변경

5. Spring 프로젝트와 연동

1) 라이브러리 추가 (build.gradle) 

implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'

 

2) application.yml 파일에 내용 추가

cloud:
  aws:
    s3:
      bucket: <S3 버킷 이름>
    credentials:
      access-key: <저장해놓은 액세스 키>
      secret-key: <저장해놓은 비밀 액세스 키>
    region:
      static: ap-northeast-2
      auto: false
    stack:
      auto: false

 

3) S3Config.java 생성

@Configuration
public class S3Config {

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

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

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

    @Bean
    public AmazonS3Client amazonS3Client() {
        BasicAWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);

        return (AmazonS3Client) AmazonS3ClientBuilder
                .standard()
                .withRegion(region)
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .build();
    }
}

 

4) 파일 업로드 구현

@Service
@RequiredArgsConstructor
public class S3UploadService {

    private final AmazonS3 amazonS3;

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

    public String saveFile(MultipartFile multipartFile) throws IOException {
        String originalFilename = multipartFile.getOriginalFilename();

        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(multipartFile.getSize());
        metadata.setContentType(multipartFile.getContentType());

        amazonS3.putObject(bucket, originalFilename, multipartFile.getInputStream(), metadata);
        return amazonS3.getUrl(bucket, originalFilename).toString();
    }
}

 

5) HTML 파일에서 이미지 미리보기 구현

String url = amazonS3.getUrl(bucket, filename).toString();

 

이 url을 Model에 담아 HTML파일로 전송

Thymeleaf 이용해 src에 넣어주면 화면에서 이미지 미리보기 가능

<img th:src="${s3ImageUrl}"/>

 

6) 파일 삭제 구현

public void deleteImage(String originalFilename)  {
    amazonS3.deleteObject(bucket, originalFilename);
}

 

728x90

BELATED ARTICLES

more