Android Apps

Uploading File To Amazon S3

android amzon upload file to amazon s3
Written by Yasir Ameen

In terms of upload and downloading file using your moblie device is not new. We already have most of the tutorials available online which is describing how to upload and download file. In this tutorial i will describe you, how you can upload and download file directly to/from Amazon S3 using android client.

Note : This tutorials assume that you have alrady configured your Amazon S3 and you have Api Key and Secret.

 

amazon s3 file uploads

What Is Amazon S3 ?

S3 (Simple Storage Service) is a service provided by Amazon which is highly scalable object storage in the cloud. You can access Amazon S3 directly from your app using AWS SDK.

 

Configuring Amazon SDK In Our Project.

Create an application , call it Amazon S3 open build.gradle(Module:app) and pase the following.

compile 'com.amazonaws:aws-android-sdk-core:2.3.3'
compile 'com.amazonaws:aws-android-sdk-s3:2.3.3'
compile 'com.amazonaws:aws-android-sdk-ddb:2.3.3'

 

Important : Paste following service in your manifies file.

<service
    android:name="com.amazonaws.mobileconnectors.s3.transferutility.TransferService"
    android:enabled="true" />

Understanding A Concept Step By Step

  1. You first create AWS Credentials for accessing S3 using BasicAWSCredentails class
  2. Pass AWS Credentials to AmazonS3 instance
  3. You then pass AmazonS3 object to TransferUtility class
  4. You assign your BucketName, FileName  and FileObject(which is to be transefer) to TransferObserver class
  5. Finally you track your transfer details using setTransferListener of TransferObserver class

 

 

Creating BasicAWSCredentials And Passing It To AmazonS3Client

Firstly create Amazon S3 BasicAWSCredentials by passing following. For now you only need AccessKeyID and SecretKey.

amazon s3 credentials

See the Code Snippet.

AmazonS3Client s3;
BasicAWSCredentials credentials;

String key = "FK5382F0HJ409J2309";
String secret = "FAJ9E280F39FA0FUA90FSP/ACN3820F"; 
credentials = new BasicAWSCredentials(key,secret);
s3 = new AmazonS3Client(credentials);

 

Passing AmazonS3 Client to TransferUtlityObject

After creating credentials, pass these credentials in TransfertUtiliy  constructor.

AmazonS3Client s3;
BasicAWSCredentials credentials;
TransferUtility transferUtility;

String key = "FK5382F0HJ409J2309";
String secret = "FAJ9E280F39FA0FUA90FSP/ACN3820F";

credentials = new BasicAWSCredentials(key,secret);
s3 = new AmazonS3Client(credentials);


transferUtility = new TransferUtility(s3, this);

 

Uplaoding File Using TransferUtilityClass

In order to upload file, you call .upload(…) method of TransferUtility class and pass three arguments in .upload(…) method, following code will start upload your file to s3.

amazon se upload

see the code snippet

AmazonS3Client s3;
BasicAWSCredentials credentials;
TransferUtility transferUtility;
TransferObserver observer;

String key = "FK5382F0HJ409J2309";
String secret = "FAJ9E280F39FA0FUA90FSP/ACN3820F";

credentials = new BasicAWSCredentials(key,secret);
s3 = new AmazonS3Client(credentials);


transferUtility = new TransferUtility(s3, this);

observer = transferUtility.upload(
        "media.invision.com",
        "MyfileName",
        new File("someImage.jpg")
);

 

Tracking Transer Using TransferObserver Listener

You can track upload by calling observerListener.

AmazonS3Client s3;
BasicAWSCredentials credentials;
TransferUtility transferUtility;
TransferObserver observer;

String key = "FK5382F0HJ409J2309";
String secret = "FAJ9E280F39FA0FUA90FSP/ACN3820F";

credentials = new BasicAWSCredentials(key,secret);
s3 = new AmazonS3Client(credentials);


transferUtility = new TransferUtility(s3, this);

observer = transferUtility.upload(
        "media.invision.com",
        "MyfileName",
        new File("someImage.jpg")
);

observer.setTransferListener(new TransferListener() {
    @Override
    public void onStateChanged(int id, TransferState state) {

    }

    @Override
    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {

    }

    @Override
    public void onError(int id, Exception ex) {

    }
});

 

Pausing / Resuming a S3 Transfer

Sometimes we face different issue like, app carshing  or loses internet connectiviy. So we can pause our transfer or resume using the following methods.

//To Pause a Single Transfer
transferUtility.pause(idOfTransferToBePaused);

//To Pause All Uploads
transferUtility.pauseAllWithType(TransferType.UPLOAD);

//To Resuming a Single Transfer
transferUtility.resume(idOfTransferToBeResumed);

//To Cancel a Single Transfer
transferUtility.cancel(idToBeCancelled);

//To Cancel All Transfer (Uploads)
transferUtility.cancelAllWithType(TransferType.UPLOAD);

Complete Code Of File Uploading

 


public class MainActivity extends AppCompatActivity {


    ProgressBar pb;
    Button btn_upload;
    TextView _status;

    AmazonS3Client s3;
    BasicAWSCredentials credentials;
    TransferUtility transferUtility;
    TransferObserver observer;

    String key = "FK5382F0HJ409J2309";
    String secret = "FAJ9E280F39FA0FUA90FSP/ACN3820F";
    String path = "someFilePath.png";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        pb = (ProgressBar) findViewById(R.id.progressBar);
        btn_upload = (Button) findViewById(R.id.btn_upload);
        _status = (TextView) findViewById(R.id.txt_progress);

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                credentials = new BasicAWSCredentials(key,secret);
                s3 = new AmazonS3Client(credentials);
                transferUtility = new TransferUtility(s3, MainActivity.this);


                File file = new File(path);
                if(!file.exists()) {
                    Toast.makeText(MainActivity.this, "File Not Found!", Toast.LENGTH_SHORT).show();
                    return;
                }
                observer = transferUtility.upload(
                        "media.invision.com",
                        "Test_Video",
                        file
                );

                observer.setTransferListener(new TransferListener() {
                    @Override
                    public void onStateChanged(int id, TransferState state) {

                        if (state.COMPLETED.equals(observer.getState())) {

                            Toast.makeText(MainActivity.this, "File Upload Complete", Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onProgressChanged(int id, long bytesCurrent, long bytesTotal) {



                        long _bytesCurrent = bytesCurrent;
                        long _bytesTotal = bytesTotal;

                        float percentage =  ((float)_bytesCurrent /(float)_bytesTotal * 100);
                        Log.d("percentage","" +percentage);
                        pb.setProgress((int) percentage);
                        _status.setText(percentage + "%");
                    }

                    @Override
                    public void onError(int id, Exception ex) {

                        Toast.makeText(MainActivity.this, "" + ex.getMessage(), Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
        
    }
    
}

 

 

About the author

Yasir Ameen

I'm a programmer, teacher, and speaker. I work out of my home in Pakistan, Karachi for the Mobile, especially Android Platform. I discuss about technology, gadgets, codes, the devices we’re going and we’ve been. I’m excited about community, social equity, and media.

Leave a Comment