Page updated Jan 16, 2024

Set up Amplify Storage

Amplify Android v1 is now in Maintenance Mode until May 31st, 2024. This means that we will continue to include updates to ensure compatibility with backend services and security. No new features will be introduced in v1.

Please use the latest version (v2) of Amplify Library for Android to get started.

If you are currently using v1, follow these instructions to upgrade to v2.

Amplify libraries should be used for all new cloud connected applications. If you are currently using the AWS Mobile SDK for Android, you can access the documentation here.

The Amplify Storage category provides an interface for managing user content for your app in public, protected, or private storage buckets. The Storage category comes with default built-in support for Amazon Simple Storage Service (S3). The Amplify CLI helps you to create and configure the storage buckets for your app. The Amplify AWS S3 Storage plugin leverages Amazon S3.

Goal

To setup and configure your application with Amplify Storage and go through a simple upload file example

Prerequisites

  • An Android application targeting Android API level 16 (Android 4.1) or above

Provision backend storage

To start provisioning storage resources in the backend, go to your project directory and execute the command:

1amplify add storage

Enter the following when prompted:

1? Please select from one of the below mentioned services:
2 `Content (Images, audio, video, etc.)`
3? You need to add auth (Amazon Cognito) to your project in order to add storage for user files. Do you want to add auth now?
4 `Yes`
5? Do you want to use the default authentication and security configuration?
6 `Default configuration`
7? How do you want users to be able to sign in?
8 `Username`
9? Do you want to configure advanced settings?
10 `No, I am done.`
11? Please provide a friendly name for your resource that will be used to label this category in the project:
12 `S3friendlyName`
13? Please provide bucket name:
14 `storagebucketname`
15? Who should have access:
16 `Auth and guest users`
17? What kind of access do you want for Authenticated users?
18 `create/update, read, delete`
19? What kind of access do you want for Guest users?
20 `create/update, read, delete`
21? Do you want to add a Lambda Trigger for your S3 Bucket?
22 `No`

To push your changes to the cloud, execute the command:

1amplify push

Upon completion, amplifyconfiguration.json will be updated to reference a newly provisioned S3 bucket. Note that this file should already be a part of your project if you followed the Project setup walkthrough.

Install Amplify Libraries

Expand Gradle Scripts, open build.gradle (Module :app). You will already have configured Amplify by following the steps in the Project Setup walkthrough.

Add these libraries into the dependencies block:

1dependencies {
2 implementation 'com.amplifyframework:aws-storage-s3:ANDROID_V1_VERSION'
3 implementation 'com.amplifyframework:aws-auth-cognito:ANDROID_V1_VERSION'
4}

aws-auth-cognito is used to provide authentication for Amazon S3.

Click Sync Now.

Initialize Amplify Storage

To initialize the Amplify Auth and Storage categories you call Amplify.addPlugin() method for each category. To complete initialization call Amplify.configure().

Add the following code to your onCreate() method in your application class:

1Amplify.addPlugin(new AWSCognitoAuthPlugin());
2Amplify.addPlugin(new AWSS3StoragePlugin());

Your class will look like this:

1public class MyAmplifyApp extends Application {
2 @Override
3 public void onCreate() {
4 super.onCreate();
5
6 try {
7 // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins
8 Amplify.addPlugin(new AWSCognitoAuthPlugin());
9 Amplify.addPlugin(new AWSS3StoragePlugin());
10 Amplify.configure(getApplicationContext());
11
12 Log.i("MyAmplifyApp", "Initialized Amplify");
13 } catch (AmplifyException error) {
14 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
15 }
16 }
17}
1Amplify.addPlugin(AWSCognitoAuthPlugin())
2Amplify.addPlugin(AWSS3StoragePlugin())

Your class will look like this:

1class MyAmplifyApp : Application() {
2 override fun onCreate() {
3 super.onCreate()
4
5 try {
6 // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins
7 Amplify.addPlugin(AWSCognitoAuthPlugin())
8 Amplify.addPlugin(AWSS3StoragePlugin())
9 Amplify.configure(applicationContext)
10
11 Log.i("MyAmplifyApp", "Initialized Amplify")
12 } catch (error: AmplifyException) {
13 Log.e("MyAmplifyApp", "Could not initialize Amplify", error)
14 }
15 }
16}
1RxAmplify.addPlugin(new AWSCognitoAuthPlugin());
2RxAmplify.addPlugin(new AWSS3StoragePlugin());

Your class will look like this:

1public class MyAmplifyApp extends Application {
2 @Override
3 public void onCreate() {
4 super.onCreate();
5
6 try {
7 // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins
8 RxAmplify.addPlugin(new AWSCognitoAuthPlugin());
9 RxAmplify.addPlugin(new AWSS3StoragePlugin());
10 RxAmplify.configure(getApplicationContext());
11
12 Log.i("MyAmplifyApp", "Initialized Amplify");
13 } catch (AmplifyException error) {
14 Log.e("MyAmplifyApp", "Could not initialize Amplify", error);
15 }
16 }
17}

Note that because the storage category requires auth, you will need to either configure guest access or sign in a user before using features in the storage category.

Uploading data to your bucket

To upload to S3 from a data object, specify the key and the data object to be uploaded.

1private void uploadFile() {
2 File exampleFile = new File(getApplicationContext().getFilesDir(), "ExampleKey");
3
4 try {
5 BufferedWriter writer = new BufferedWriter(new FileWriter(exampleFile));
6 writer.append("Example file contents");
7 writer.close();
8 } catch (Exception exception) {
9 Log.e("MyAmplifyApp", "Upload failed", exception);
10 }
11
12 Amplify.Storage.uploadFile(
13 "ExampleKey",
14 exampleFile,
15 result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()),
16 storageFailure -> Log.e("MyAmplifyApp", "Upload failed", storageFailure)
17 );
18}
1private fun uploadFile() {
2 val exampleFile = File(applicationContext.filesDir, "ExampleKey")
3 exampleFile.writeText("Example file contents")
4
5 Amplify.Storage.uploadFile("ExampleKey", exampleFile,
6 { Log.i("MyAmplifyApp", "Successfully uploaded: ${it.key}") },
7 { Log.e("MyAmplifyApp", "Upload failed", it) }
8 )
9}
1private suspend fun uploadFile() {
2 val exampleFile = File(applicationContext.filesDir, "ExampleKey")
3 exampleFile.writeText("Example file contents")
4
5 val upload = Amplify.Storage.uploadFile("ExampleKey", exampleFile)
6 try {
7 val result = upload.result()
8 Log.i("MyAmplifyApp", "Successfully uploaded: ${result.key}")
9 } catch (error: StorageException) {
10 Log.e("MyAmplifyApp", "Upload failed", error)
11 }
12}
1private void uploadFile() {
2 File exampleFile = new File(getApplicationContext().getFilesDir(), "ExampleKey");
3
4 try {
5 BufferedWriter writer = new BufferedWriter(new FileWriter(exampleFile));
6 writer.append("Example file contents");
7 writer.close();
8 } catch (Exception exception) {
9 Log.e("MyAmplifyApp", "Upload failed", exception);
10 }
11
12 RxProgressAwareSingleOperation<StorageUploadFileResult> upload =
13 RxAmplify.Storage.uploadFile("ExampleKey", exampleFile);
14
15 upload
16 .observeResult()
17 .subscribe(
18 result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()),
19 error -> Log.e("MyAmplifyApp", "Upload failed", error)
20 );
21}

Upon successfully executing this code, you should see a new folder in your bucket, called public. It should contain a file called ExampleKey, whose contents is Example file contents.

Next Steps

Congratulations! You've uploaded a file to an s3 bucket. Check out the following links to see other Amplify Storage use cases: