본문 바로가기
컴퓨터관련

AWS S3 Uploader Progress 이용하여 uploading 하기

by 기록이답이다 2017. 1. 27.
반응형

AWS S3를 이용하는데 로컬에 있는 파일을 업로드를 해야 한다.

일일이 하나씩해도 되지만...


자바를 이용해서도 할 수 있다.


우선 AWS-LIB를 (https://aws.amazon.com/ko/sdk-for-java/) 여기에서 받아서

프로젝트에 import한다.


업로드 단계는 다음과 같다.


1. ProfileCredentialsProvider 를 이용해서 AWSCredentials 을 얻어온다.

1
2
credentials = new ProfileCredentialsProvider()
                       .getCredentials( credential파일위치, 프로파일이름 );

~/.aws/  디렉토리에  credentials 파일을 만들어두면 아래와 같이 하지 않고 위와 같이 바로 적용할 수 있다.

1
credentials = new ProfileCredentialsProvider().getCredentials();


credential 파일은 다음과 같이 만들 수 있다.

메모장을 열어 아래의 내용을 입력하면 된다.


1
2
3
[default] <- profile의 이름이다.
aws_access_key_id=aws_access_key_id 를 입력한다.
aws_secret_access_key=aws_secret_access_key 를 입력한다.

위에서 얻어온 credentials를 가지고 AmazonS3 객체를 생성후 Region을 설정해준다.

1
2
3
AmazonS3 s3 = new AmazonS3Client(credentials);
Region usWest2 = Region.getRegion(Regions.US_EAST_1);
s3.setRegion(usWest2);

위의 단계가 AmazonS3 객체를 얻어와 region을 설정하는 단계이다.

이제 s3객체를 얻어왔으니 TransferManager PutObjectRequest를 이용하여 업로드를 구현하면 된다.


TransferManager와 PutObjectRequest객체를 생성한다.

1
2
TransferManager tx = new TransferManager(s3);
PutObjectRequest request = new PutObjectRequest(bucketName, keyName, 업로드할 파일);

transferManager 객체를 이용하여 putObject객체를 업로드해준다.

1
2
Upload upload = tx.upload(request);
double totalSize = upload.getProgress().getTotalBytesToTransfer(); // 전체 파일사이즈

upload가 잘되는지 확인하기 위해 ProgressListener를 putObjectRequest에 지정할 수 있다.

1
request.withGeneralProgressListener(progressListener);


progressListener는 아래와 같다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
int prevPer = -1;
public ProgressListener progressListener = new ProgressListener() {
    double trans = 0;
    @SuppressWarnings("deprecation")
    public void progressChanged(ProgressEvent progressEvent) {
        if (upload == null) return;
 
        synchronized (this) {
            trans += progressEvent.getBytesTransferred();
            int currPer = (int)upload.getProgress().getPercentTransferred();
            if(prevPer < currPer) {
                System.out.println(request.getKey() + " - " + numberFormat(trans/1000) + " / " + numberFormat(totalSize/1000) + " : " + currPer + "%");
            }
            prevPer = currPer;
        }
         
        switch (progressEvent.getEventCode()) {
        case ProgressEvent.COMPLETED_EVENT_CODE:
            System.out.println("100%"); // 전송완료
            trans = 0;
            break;
        case ProgressEvent.FAILED_EVENT_CODE:
            try {
                AmazonClientException e = upload.waitForException();
            } catch (InterruptedException e) {}
            break;
        }
    }
};


전체소스는 다음과 같다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package bugnote.upload.s3;
 
import java.io.File;
import java.text.DecimalFormat;
 
import com.amazonaws.AmazonClientException;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.auth.profile.ProfileCredentialsProvider;
import com.amazonaws.event.ProgressEvent;
import com.amazonaws.event.ProgressListener;
import com.amazonaws.regions.Region;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3Client;
import com.amazonaws.services.s3.model.PutObjectRequest;
import com.amazonaws.services.s3.transfer.TransferManager;
import com.amazonaws.services.s3.transfer.Upload;
 
public class S3Uploader {
    private AmazonS3 s3;
    private String bucketName;
    private Upload upload;
    private PutObjectRequest request = null;
    private static TransferManager tx;
    private double totalSize;
     
    public static void main(String[] args) {
        new S3Uploader();
    }
     
    public S3Uploader() {
         
        AWSCredentials credentials = new ProfileCredentialsProvider("credential파일위치", "프로파일이름").getCredentials();
        s3 = new AmazonS3Client(credentials);
        Region region = Region.getRegion(Regions.US_EAST_1);
        s3.setRegion(region);
         
        this.bucketName = "s3 버킷이름";
        this.tx = new TransferManager(s3);
         
        File file = new File("업로드할파일");
        doUpload(file);
    }
 
    public void doUpload(File f) {
        // 디렉토리/디렉토리/파일명 으로 keyname을 주기위해 파일명을 제외한 디렉토리를 구한다.
        String pwd = f.getParent().substring(f.getParent().lastIndexOf("\\")+1);
        String s3Key = pwd + "/" + f.getName();
        request = new PutObjectRequest(bucketName, s3Key, f).withGeneralProgressListener(progressListener);
         
        upload = this.tx.upload(request);
        totalSize = upload.getProgress().getTotalBytesToTransfer();
    }
 
    private String numberFormat(Object value) {
        DecimalFormat df = new DecimalFormat("#.##");
        return df.format( value );
    }
     
    int prevPer = -1;
    public ProgressListener progressListener = new ProgressListener() {
        double trans = 0;
        @SuppressWarnings("deprecation")
        public void progressChanged(ProgressEvent progressEvent) {
            if (upload == null) return;
 
            synchronized (this) {
                trans += progressEvent.getBytesTransferred();
                int currPer = (int)upload.getProgress().getPercentTransferred();
                if(prevPer < currPer) {
                    System.out.println(request.getKey() + " - " + numberFormat(trans/1000) + " / " + numberFormat(totalSize/1000) + " : " + currPer + "%");
                }
                prevPer = currPer;
            }
             
            switch (progressEvent.getEventCode()) {
            case ProgressEvent.COMPLETED_EVENT_CODE:
                System.out.println("100%"); // 전송완료
                trans = 0;
                break;
            case ProgressEvent.FAILED_EVENT_CODE:
                try {
                    AmazonClientException e = upload.waitForException();
                } catch (InterruptedException e) {}
                break;
            }
        }
    };
}

java를 이용한 s3에 file upload 종료!!!


반응형