본문 바로가기

Spring Boot

[Spring Boot] AWS S3에 파일 업로드,복사,삭제하기

pom.xml ( aws-java-sdk-s3 의존성 추가 )

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.7.1</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.example</groupId>
	<artifactId>demo</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>demo</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>1.8</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		
		<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk</artifactId>
            <version>1.12.255</version>
        </dependency>
		
		<dependency>
            <groupId>com.amazonaws</groupId>
            <artifactId>aws-java-sdk-s3</artifactId>
            <version>1.12.255</version>
        </dependency>
        
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>

DemoApplication.java (@SpringBootApplication)

 

package com.example.demo;

import java.io.File;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication implements CommandLineRunner{
	
	@Autowired
	private AwsS3 awsS3;
 
	public static void main(String[] args) {
		SpringApplication.run(DemoApplication.class, args);
	}
	
	@Override
	public void run(String... args) throws Exception {
		
        System.out.println("aws S3 Test run start");
		
        File file = new File("D://workspace_springboot/examples.xlsx"); // 업로드할 파일 경로
        String s3Path = "javatest/examples.xlsx"; // S3에 저장될 경로 및 파일 이름
        String s3TargetPath = "javatest/examples_copy.xlsx"; // S3에서 복사할 target 이름
        
        upload(file, s3Path); // S3 파일 업로드
        copy(s3Path,s3TargetPath); // S3 파일 복제
//        delete(s3Path); // S3 파일 삭제
        
        System.out.println("aws S3 Test run stop");
	}
	
	public  void upload(File file, String s3Path) {
        awsS3.upload(file, s3Path);
    }

    public void copy(String s3SourcePath, String s3TargetPath) {
        awsS3.copy(s3SourcePath, s3TargetPath);
    }

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

}

 

AwsS3.java (Service)

package com.example.demo;
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.ObjectMetadata;
import com.amazonaws.services.s3.model.PutObjectRequest;
import java.io.File;
import java.io.InputStream;

import org.springframework.stereotype.Service;

@Service
public class AwsS3 {

    //Amazon-s3-sdk 
    private AmazonS3 s3Client;
    final private String accessKey = "AKIXXXXXXXXXXXXXXXXX"; // IAM에서 발급받은 accessKey
    final private String secretKey = "p4MHrXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; // IAM에서 발급받은 secretKey
    private Regions clientRegion = Regions.AP_NORTHEAST_2; // region
    private String bucket = "sample-pslab-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 s3Path) {
        uploadToS3(new PutObjectRequest(this.bucket, s3Path, file));
    }

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

        uploadToS3(new PutObjectRequest(this.bucket, s3Path, 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 s3SourcePath, String s3TargetPath) {
        try {
            //Copy 객체 생성
            CopyObjectRequest copyObjRequest = new CopyObjectRequest(
                    this.bucket,
                    s3SourcePath,
                    this.bucket,
                    s3TargetPath
            );
            //Copy
            this.s3Client.copyObject(copyObjRequest);

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

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

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

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


}

 

[참고]

[AWS] JAVA S3로 파일 업로드, 복사, 삭제 하기

'Spring Boot' 카테고리의 다른 글

[Spring Boot] Lombok 오류  (0) 2022.08.31
[Spring Boot] REST API 결과 AWS S3에 저장하기  (0) 2022.07.11
[Spring Boot] OkHttp REST Client  (0) 2022.07.11