S3를 생성하지 않았다면 다음 글을 참고해주세요.
2020/11/17 - [IT/AWS] - [AWS] Amazon S3 생성 방법 (Amazon Simple Storage Service)
S3 용어를 알고 싶다면 다음글을 참고해주세요.
2020/11/17 - [IT/AWS] - [AWS] Amazon S3 (Simple Storage Service)란 무엇인가?
 

[AWS] Amazon S3 (Simple Storage Service)란 무엇인가?

1. Amazon S3란? Simple Storage Service의 약자로 내구성과 확장성이 뛰어난 스토리지 서비스입니다. 2. Amazon S3 용어 설명 bucket S3에서 생성되는 최상위 디렉토리이며 디렉터리와 객체를 저장하는 컨테

bamdule.tistory.com

1. pom.xml

...        
        <!-- https://mvnrepository.com/artifact/com.amazonaws/aws-java-sdk-s3 -->
        <dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.11.901</version>
        </dependency>
...        

 

2. AwsS3.java

아무나 S3에 파일을 업로드 하지 못하게 막으려면 IAM에서 accessKey와 secretKey를 발급 받아야 합니다.
만약 누구나 업로드가 가능하게 하려면 S3 권한 > 버킷 정책에서 해당 정책을 생성한 후 적용해 주어야 합니다.
import com.amazonaws.AmazonServiceException;
import com.amazonaws.SdkClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.amazonaws.services.s3.model.CopyObjectRequest;
import com.amazonaws.services.s3.model.DeleteObjectRequest;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;

public class AwsS3 {

    //Amazon-s3-sdk 
    private AmazonS3 s3Client;
    final private String accessKey = "IAM에서 발급받은 accessKey";
    final private String secretKey = "IAM에서 발급받은 secretKey";
    private Regions clientRegion = Regions.AP_NORTHEAST_2;
    private String bucket = "bamdule-bucket";

    private AwsS3() {
        createS3Client();
    }

    //singleton pattern
    static private AwsS3 instance = null;
    
    public static AwsS3 getInstance() {
        if (instance == null) {
            return new AwsS3();
        } else {
            return instance;
        }
    }

    //aws S3 client 생성
    private void createS3Client() {

        AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
        this.s3Client = AmazonS3ClientBuilder
                .standard()
                .withCredentials(new AWSStaticCredentialsProvider(credentials))
                .withRegion(clientRegion)
                .build();
    }

    public void upload(File file, String key) {
        uploadToS3(new PutObjectRequest(this.bucket, key, file));
    }

    public void upload(InputStream is, String key, String contentType, long contentLength) {
        ObjectMetadata objectMetadata = new ObjectMetadata();
        objectMetadata.setContentType(contentType);
        objectMetadata.setContentLength(contentLength);

        uploadToS3(new PutObjectRequest(this.bucket, key, is, objectMetadata));
    }

    //PutObjectRequest는 Aws S3 버킷에 업로드할 객체 메타 데이터와 파일 데이터로 이루어져있다.
    private void uploadToS3(PutObjectRequest putObjectRequest) {

        try {
            this.s3Client.putObject(putObjectRequest);
            System.out.println(String.format("[%s] upload complete", putObjectRequest.getKey()));

        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void copy(String orgKey, String copyKey) {
        try {
            //Copy 객체 생성
            CopyObjectRequest copyObjRequest = new CopyObjectRequest(
                    this.bucket,
                    orgKey,
                    this.bucket,
                    copyKey
            );
            //Copy
            this.s3Client.copyObject(copyObjRequest);

            System.out.println(String.format("Finish copying [%s] to [%s]", orgKey, copyKey));

        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }

    public void delete(String key) {
        try {
            //Delete 객체 생성
            DeleteObjectRequest deleteObjectRequest = new DeleteObjectRequest(this.bucket, key);
            //Delete
            this.s3Client.deleteObject(deleteObjectRequest);
            System.out.println(String.format("[%s] deletion complete", key));

        } catch (AmazonServiceException e) {
            e.printStackTrace();
        } catch (SdkClientException e) {
            e.printStackTrace();
        }
    }


}
파일을 업로드하려면 PutObjectRequest 객체를 생성해야합니다. PutObjectRequest 객체를 생성하는 방법은 두가지가 있는데,
첫번째는 File 객체와 key값을 이용해 만드는 방법이고, 두번째는 InputStream과 key값 그리고 파일 정보(ContentType, file Length 등)를 이용해 만드는 방법입니다. 여기서 key 값은 버킷 내에서 객체를 찾기위해 사용되는 고유 식별자를 의미합니다.

 

3. Main.java

import java.io.File;

public class Main {

    public AwsS3 awsS3 = AwsS3.getInstance();

    public static void main(String[] args) {

        Main main = new Main();

        File file = new File("D://4.png");
        String key = "img/my-img.png";
        String copyKey = "img/my-img-copy.png";

        main.upload(file, key);
//        main.copy(key, copyKey);
//        main.delete(key);
    }

    public void upload(File file, String key) {
        awsS3.upload(file, key);
    }

    public void copy(String orgKey, String copyKey) {
        awsS3.copy(orgKey, copyKey);
    }

    public void delete(String key) {
        awsS3.delete(key);
    }

}

+ Recent posts