투케이2K

958. (Android/Java) [유틸 파일] getS3FileUpload - Aws S3 버킷 저장소 파일 업로드 수행 - AmazonS3 File Upload 본문

Android

958. (Android/Java) [유틸 파일] getS3FileUpload - Aws S3 버킷 저장소 파일 업로드 수행 - AmazonS3 File Upload

투케이2K 2025. 3. 15. 19:28

[개발 환경 설정]

개발 툴 : AndroidStudio

개발 언어 : Java / Kotlin

 

[소스 코드]

// --------------------------------------------------------------------------------------
[개발 및 테스트 환경]
// --------------------------------------------------------------------------------------

- 언어 : Java / Kotlin

- 개발 툴 : AndroidStudio

- 기술 구분 : Aws / S3 / Bucket

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[사전) 필요 설정 정리] : build.gradle 의존성 부여
// --------------------------------------------------------------------------------------

// [AWS] : [target 31 이상 의존성]
implementation 'com.amazonaws:aws-android-sdk-s3:2.57.0'
implementation 'com.amazonaws:aws-android-sdk-iot:2.57.0'
implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.57.0'


// [AWS] : [target 31 미만 의존성]
implementation 'com.amazonaws:aws-android-sdk-s3:2.16.13'
implementation 'com.amazonaws:aws-android-sdk-iot:2.16.13'
implementation 'com.amazonaws:aws-android-sdk-mobile-client:2.16.13'

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[사전) AmazonS3Client 초기화 방법
// --------------------------------------------------------------------------------------

https://blog.naver.com/kkh0977/223797255512

// --------------------------------------------------------------------------------------





// --------------------------------------------------------------------------------------
[Java : 소스 코드]
// --------------------------------------------------------------------------------------

public Observable<Boolean> getS3FileUpload(String awsBucket, String fileName, File file) {
    S_Log._D_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 수행", new String[]{
            "awsBucketName :: " + String.valueOf(awsBucket),
            "fileName :: " + String.valueOf(fileName)
    });

    return Observable.create(subscriber -> {

        try {

            if (s3Client != null && mMainCtx != null){

                if (C_Util.stringNotNull(awsBucket) == true && C_Util.stringNotNull(fileName) == true && file != null){

                    new Thread(() -> {

                        TransferUtility transferUtility = TransferUtility.builder().s3Client(s3Client).context(mMainCtx.getApplicationContext()).build();
                        TransferNetworkLossHandler.getInstance(mMainCtx.getApplicationContext());

                        TransferObserver uploadObserver = transferUtility.upload(awsBucket, fileName, file); // TODO [bucket / file 이름 / file 객체]

                        uploadObserver.setTransferListener(new TransferListener() {
                            @Override
                            public void onStateChanged(int id, TransferState state) {
                                if (state == TransferState.COMPLETED) {
                                    S_Log._W_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 완료", new String[]{"StateChanged :: COMPLETED"});

                                    if (subscriber != null && subscriber.isDisposed() == false){
                                        subscriber.onNext(true);
                                        subscriber.onComplete();
                                    }
                                }
                                else if (state == TransferState.FAILED) {
                                    S_Log._E_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 에러", new String[]{"StateChanged :: FAILED"});

                                    if (subscriber != null && subscriber.isDisposed() == false){
                                        subscriber.onError(new Throwable("[Error] : StateChanged : FAILED"));
                                        subscriber.onComplete();
                                    }
                                }
                                else if (state == TransferState.CANCELED) {
                                    S_Log._E_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 에러", new String[]{"StateChanged :: CANCELED"});

                                    if (subscriber != null && subscriber.isDisposed() == false){
                                        subscriber.onError(new Throwable("[Error] : StateChanged : CANCELED"));
                                        subscriber.onComplete();
                                    }
                                }
                                else {
                                    S_Log.w("S3_UPLOAD", ">>>>>>>>>>>>>>>>>>>>>>>>>>>> [StateChanged] : ["+String.valueOf(state)+"] >>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                }
                            }
                            @Override
                            public void onProgressChanged(int id, long current, long total) {
                                try {
                                    int done = (int) (((double) current / total) * 100.0);

                                    S_Log.d("S3_UPLOAD", ">>>>>>>>>>>>>>>>>>>>>>>>>>>> [Progress] : ["+String.valueOf(done)+"] >>>>>>>>>>>>>>>>>>>>>>>>>>>>");
                                }
                                catch (Exception es){
                                    es.printStackTrace();
                                }
                            }
                            @Override
                            public void onError(int id, Exception ex) {
                                S_Log._E_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 에러", new String[]{"Upload Exception :: " + String.valueOf(ex.getMessage())});

                                if (subscriber != null && subscriber.isDisposed() == false){
                                    subscriber.onError(new Throwable("[Error] : Upload Exception : " + String.valueOf(ex.getMessage())));
                                    subscriber.onComplete();
                                }
                            }
                        });

                    }).start();

                }
                else {
                    S_Log._E_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 에러", new String[]{"Error :: input data is null"});

                    if (subscriber != null && subscriber.isDisposed() == false){
                        subscriber.onError(new Throwable("[Error] : input data is null"));
                        subscriber.onComplete();
                    }
                }

            }
            else {
                S_Log._E_(ACTIVITY_NAME + " :: getS3FileUpload :: S3 특정 버킷 파일 업로드 에러", new String[]{"Error :: s3Client is null"});

                if (subscriber != null && subscriber.isDisposed() == false){
                    subscriber.onError(new Throwable("[Error] : s3Client is null"));
                    subscriber.onComplete();
                }

            }

        } catch (final Exception e){
            S_Log._printStackTrace_(null, S_FinalData.LOG_BUG_STATE, null, e);

            try {
                if (subscriber != null && subscriber.isDisposed() == false){
                    subscriber.onError(new Throwable("[Exception] : " + String.valueOf(e.getMessage())));
                    subscriber.onComplete();
                }
            }
            catch (Exception ex){
                ex.printStackTrace();
            }
        }

    });
}

// --------------------------------------------------------------------------------------






// --------------------------------------------------------------------------------------
[참고 사이트]
// --------------------------------------------------------------------------------------

[S3 (Amazon Simple Storage Service) 버킷 저장소 개념 및 설명 정리]

https://blog.naver.com/kkh0977/223733087281?trackingCode=blog_bloghome_searchlist


[S3 (Amazon Simple Storage Service) 버킷 저장소에 파일 업로드 방법]

https://blog.naver.com/kkh0977/223733106182?trackingCode=blog_bloghome_searchlist


[AccessKey , SecretKey 사용해 Aws S3 버킷 스토리지 AmazonS3Client 초기화 방법]

https://blog.naver.com/kkh0977/223797255512

// --------------------------------------------------------------------------------------
 
반응형
Comments