Simplifying AWS S3 File Uploads with the Android Library
Tags: android, s3, aws, upload
Published: 2023-08-09 22:18:18

Uploading files to AWS S3 can be tricky

Uploading files to an AWS S3 bucket is a common task in many apps. But it can be tricky, especially if you want to preserve the file extension. That's because when you use a PUT request with a pre-signed URL, the file extension may not be retained during the upload process. This can lead to complications, such as triggering specific actions based on file formats.

I created a library to make file uploads to S3 easier

To address this issue, I created an [Android library](https://github.com/mavinomichael/AWS-S3-Upload-Library). It's a simple, easy-to-use and makes it a breeze to upload files to AWS S3 while keeping the file extension intact.In this article, we'll dive into the details of this library and guide you through the steps to seamlessly upload files to AWS S3

Here's how it works

**Step 1: Setting Up the Basics**

Begin by logging into the AWS Management Console and navigating to the S3 service. Create a new S3 bucket to store your files securely.

![Login to AWS management console and go to S3:](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fsxnsypenj78dq596ie4.png)

**Step 2: Establishing Identity Pool**

1. Search for "Cognito" in the management console and access "Federated Entities."
2. Enable access to unauthenticated identities to allow seamless and secure access.

![Create identity pool:](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/7o1suhhjlpw7yy86b5tr.png)



![Open federated entities to create a new identity pool](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x7oc9bwa4x49y5la38xe.png)



![Click on create new identity pool](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/l48on6gmjnpb7sdb22xp.png)



![Enter your App name for identity pool name and enable access to unauthenticated identities and click on create pool.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vxq5xoq8kt6bbtq6xcsz.png)



![Click on the Allow button to create two default roles associated with your identity pool: one for unauthenticated users and one for authenticated users](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/91l1quj0wd217k54usjm.png)



![Your identity pool id will be shown to you in the code snippet copy and save for later.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1d2ho6r7bhlezweumffn.png)


**Step 3: Granting Permissions**

1. Access the AWS IAM Console and select "Roles" from the side menu.
2. Search for the role named "Cognito_appnameUnath_Role" (replace "appname" with your Identity Pool name).
3. Attach the "AmazonS3FullAccess" policy to this role to grant necessary permissions.


![Grant permission to S3 bucket:](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r8yvo2r7rgh7sidqm4n5.png)




![Search for Cognito_appnameUnath_Role replace app name with your Pool Id name](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b87bggir7imasoywoyr.png)



![Select Unauth role and click on add permissions to reveal attach policy option, click on attach policy.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/663gc3bj4ioi7qlxm69d.png)



![Search for AmazonS3FullAccess](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qequlehvzw8rmqehdn3s.png)




![Attach policy or permission](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a8dr42rjeymdlxtjojho.png)


**Step 4: Integrating Dependencies**

1. Add JitPack repository to your project's settings.gradle file.
2. Include the library dependency for the AWS-S3-Upload-Library in your app's Gradle file.

```
implementation 'com.github.mavinomichael:AWS-S3-Upload-Library:1.0.1'

```

**Step 5: Utilizing the S3Uploader Object**

1. Initialize the CognitoCachingCredentialsProvider with your Identity Pool ID and region.
2. Create an object that holds your AWS keys, including Cognito Pool ID, bucket name, and regions.
3. Instantiate the S3Uploader object using the previously defined keys.
4. Use the uploadFile function to upload your desired file to S3, preserving the file extension.



```
val s3uploaderObj = S3Uploader(
    context,
    AWSKeys.BUCKET_NAME,
    AWSKeys.COGNITO_POOL_ID,
    AWSKeys.COGNITO_REGION,
    AWSKeys.BUCKET_REGION
)

fun uploadVideoToS3(videoUri: Uri, context: Context): String {
    val fileUrl = s3uploaderObj.uploadFile(
        videoUri.path!!,
        "video/mp4",
        true
    )
    return fileUrl
}

```

**Step 6: Listening to Upload Events**

Implement an event listener to capture upload events such as progress, success, error, and state changes. This ensures better control and feedback during the upload process.

```
s3uploaderObj.setOnUploadListener(object : S3UploadListener {
    override fun onSuccess(id: Int, response: String?) {
        // Handle upload success
    }

    override fun onError(id: Int, response: String?) {
        // Handle upload error
    }

    override fun onProgress(id: Int, progress: Int) {
        // Handle upload progress
    }

    override fun onStateChanged(id: Int, state: UploadState?) {
        // Handle upload state changes
    }
})

```
**Conclusion**

Uploading files to AWS S3 no longer needs to be a complex endeavour with the [AWS-S3-Upload-Library](https://github.com/mavinomichael/AWS-S3-Upload-Library), it becomes easy to upload files to S3 while keeping the file extension intact. So you can be sure that your files will be uploaded correctly, without any problems.

{% github mavinomichael/AWS-S3-Upload-Library %}