[AWS S3] SDK V2 객체 업로드

DY_DEV·2023년 7월 31일
0

PROJECT - COZYSTATES

목록 보기
3/3

https://velog.io/@11dy/AWS-S3-SDK-V2-%EA%B0%9D%EC%B2%B4-%EC%A1%B0%ED%9A%8C
객체 조회 다음으로 업로드 기능을 구현했다.

의존성

implementation 'org.springframework.cloud:spring-cloud-starter-aws:2.2.6.RELEASE'
implementation 'software.amazon.awssdk:s3:2.19.1'

aws 자격증명과 관련된 코드는 이전 글을 참고해 주세요!

MusicUploadController

package com.example.server.music.controller;

import com.example.server.music.service.AwsS3Service;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/admins/musicUpload")
@Slf4j
@Tag(name = "MusicUploadController", description = "API about MusicUpload")
public class MusicUploadController {
    private final AwsS3Service awsS3Service;
    private static final Logger logger = LoggerFactory.getLogger(MusicController.class);

    public MusicUploadController(AwsS3Service awsS3Service){
        this.awsS3Service = awsS3Service;
    }


    @PostMapping 
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file,
                                             @RequestParam("themeId") Long themeId) {
        
            awsS3Service.upload(file, themeId);
            return ResponseEntity.ok("음원이 성공적으로 업로드 되었습니다");
       
    }
  • 관리자만 업로드가 가능하게 설정했다.
  • 예외처리는 생략했다.

Service

public void upload(MultipartFile file, Long themeId)  {
        String fileName = file.getOriginalFilename();
        try {

            PutObjectRequest putObjectRequest = PutObjectRequest.builder()
                    .bucket(bucketName)
                    .key(fileName)
                    .contentType(file.getContentType())
                    .contentLength(file.getSize())
                    .metadata(Collections.singletonMap("themeId", String.valueOf(themeId))) // 메타데이터 설정하고 업로드 진행 
                    .build();

            s3Client.putObject(putObjectRequest, RequestBody.fromBytes(file.getBytes())); // 바이트 배열로 전달
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }

0개의 댓글