TIL)23.08.24(aws s3)

주민·2023년 8월 24일
0

TIL

목록 보기
70/84

aws s3 파일 업로드 하는 법!

  • application.properties
* 환경변수로 추가

#access key
cloud.aws.credentials.access-key=${ACCESS_KEY}

#secret key
cloud.aws.credentials.secret-key=${SECRET_KEY}

# 지역을 한국으로 고정
cloud.aws.region.static=ap-northeast-2

cloud.aws.s3.bucket=${BUCKET_NAME}
# CloudFormation 사용하지 않기 위함
# 실행되면 CloudFormation이 있어야만 프로젝트를 실행 할 수가 있다.
cloud.aws.stack.auto=false

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

  • AwsS3Config
@Configuration
public class AwsS3Config {
    // value 안에 있는 값을 가져와 accessKey으로 쓰겠다. => 이하 동일
    @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 basicAWSCredentials = new BasicAWSCredentials(accessKey,secretKey);
        return (AmazonS3Client) AmazonS3ClientBuilder.standard() 
                // AmazonS3ClientBuilder : Amazon S3 클라이언트를 생성하기 위한 빌더 클래스
                // standard : AmazonS3ClientBuilder 의 인스턴스 생성, 초기화
                .withRegion(region) // AmazonS3ClientBuilder 가 어떤 리전(지역)에서 동작할 것인지
                .withCredentials(new AWSStaticCredentialsProvider(basicAWSCredentials)) //생성되는 부분
                // => 클라이언트 생성에 사용할 AWS 자격 증명(인증 정보)을 설정
                .build(); // 위에서 설정한 정보를 바탕으로 클라이언트를 빌드
    }

}

- AmazonS3Client : S3 전송객체를 만들 때 필요한 클래스
=> AWS SDK 사용하여 Spring Boot 애플리케이션에서 Amazon S3 서비스와 상호 작용할 때 사용
- BasicAWSCredentials : this.accessKey = accessKey 해주는 메서드
- AWS SDK : AWS를 프로그래밍적으로 제어하기 편리하도록 제공되는 라이브러리


  • FileUploadController

@RestController
@RequestMapping("/api")
@RequiredArgsConstructor
public class FileUploadController {

    // AmazonS3Client : S3 전송객체를 만들 때 필요한 클래스
    private final AmazonS3Client amazonS3Client;

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

    @PostMapping("/upload")
    public ResponseEntity<String> uploadFile(@RequestParam("file") MultipartFile file){
        try{
            String fileName = file.getOriginalFilename(); 
            String fileURl = "http://" + bucket + fileName;
            ObjectMetadata metadata = new ObjectMetadata();
            // ObjectMetadata 에서 제공되는 set 메서드들
            metadata.setContentType(file.getContentType());
            metadata.setContentLength(file.getSize());
            amazonS3Client.putObject(bucket,fileName, file.getInputStream(), metadata);
            return ResponseEntity.ok(fileURl);
        } catch (IOException e){
            e.printStackTrace();
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}
  • MultipartFile : 웹 클라이언트가 요청을 보낼 때, HTTP 프로토콜의 바디 부분에 데이터를 여러 부분으로 나눠서 보내는 것/ 보통 파일을 전송할 때 사용
  • getOriginalFilename : 파일 이름 가져옴
  • ObjectMetadata : AWS SDK를 사용하여 Amazon S3 서비스에 객체(Object)를 업로드할 때 객체의 메타데이터(metadata)를 정의하는 데 사용되는 클래스
  • putObject : Amazon S3 서비스를 사용하여 객체를 업로드

0개의 댓글

관련 채용 정보