Set up Amplify Storage
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
- For a full example of creating Android project, please follow the project setup walkthrough
Provision backend storage
To start provisioning storage resources in the backend, go to your project directory and execute the command:
amplify add storage
Enter the following when prompted:
? Please select from one of the below mentioned services: `Content (Images, audio, video, etc.)`? 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? `Yes`? Do you want to use the default authentication and security configuration? `Default configuration`? How do you want users to be able to sign in? `Username`? Do you want to configure advanced settings? `No, I am done.`? Please provide a friendly name for your resource that will be used to label this category in the project: `S3friendlyName`? Please provide bucket name: `storagebucketname`? Who should have access: `Auth and guest users`? What kind of access do you want for Authenticated users? `create/update, read, delete`? What kind of access do you want for Guest users? `create/update, read, delete`? Do you want to add a Lambda Trigger for your S3 Bucket? `No`
To push your changes to the cloud, execute the command:
amplify 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:
dependencies { implementation 'com.amplifyframework:aws-storage-s3:ANDROID_V1_VERSION' implementation 'com.amplifyframework:aws-auth-cognito:ANDROID_V1_VERSION'}
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:
Amplify.addPlugin(new AWSCognitoAuthPlugin());Amplify.addPlugin(new AWSS3StoragePlugin());
Your class will look like this:
public class MyAmplifyApp extends Application { @Override public void onCreate() { super.onCreate();
try { // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins Amplify.addPlugin(new AWSCognitoAuthPlugin()); Amplify.addPlugin(new AWSS3StoragePlugin()); Amplify.configure(getApplicationContext());
Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } }}
Amplify.addPlugin(AWSCognitoAuthPlugin())Amplify.addPlugin(AWSS3StoragePlugin())
Your class will look like this:
class MyAmplifyApp : Application() { override fun onCreate() { super.onCreate()
try { // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins Amplify.addPlugin(AWSCognitoAuthPlugin()) Amplify.addPlugin(AWSS3StoragePlugin()) Amplify.configure(applicationContext)
Log.i("MyAmplifyApp", "Initialized Amplify") } catch (error: AmplifyException) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error) } }}
RxAmplify.addPlugin(new AWSCognitoAuthPlugin());RxAmplify.addPlugin(new AWSS3StoragePlugin());
Your class will look like this:
public class MyAmplifyApp extends Application { @Override public void onCreate() { super.onCreate();
try { // Add these lines to add the AWSCognitoAuthPlugin and AWSS3StoragePlugin plugins RxAmplify.addPlugin(new AWSCognitoAuthPlugin()); RxAmplify.addPlugin(new AWSS3StoragePlugin()); RxAmplify.configure(getApplicationContext());
Log.i("MyAmplifyApp", "Initialized Amplify"); } catch (AmplifyException error) { Log.e("MyAmplifyApp", "Could not initialize Amplify", error); } }}
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.
private void uploadFile() { File exampleFile = new File(getApplicationContext().getFilesDir(), "ExampleKey");
try { BufferedWriter writer = new BufferedWriter(new FileWriter(exampleFile)); writer.append("Example file contents"); writer.close(); } catch (Exception exception) { Log.e("MyAmplifyApp", "Upload failed", exception); }
Amplify.Storage.uploadFile( "ExampleKey", exampleFile, result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()), storageFailure -> Log.e("MyAmplifyApp", "Upload failed", storageFailure) );}
private fun uploadFile() { val exampleFile = File(applicationContext.filesDir, "ExampleKey") exampleFile.writeText("Example file contents")
Amplify.Storage.uploadFile("ExampleKey", exampleFile, { Log.i("MyAmplifyApp", "Successfully uploaded: ${it.key}") }, { Log.e("MyAmplifyApp", "Upload failed", it) } )}
private suspend fun uploadFile() { val exampleFile = File(applicationContext.filesDir, "ExampleKey") exampleFile.writeText("Example file contents")
val upload = Amplify.Storage.uploadFile("ExampleKey", exampleFile) try { val result = upload.result() Log.i("MyAmplifyApp", "Successfully uploaded: ${result.key}") } catch (error: StorageException) { Log.e("MyAmplifyApp", "Upload failed", error) }}
private void uploadFile() { File exampleFile = new File(getApplicationContext().getFilesDir(), "ExampleKey");
try { BufferedWriter writer = new BufferedWriter(new FileWriter(exampleFile)); writer.append("Example file contents"); writer.close(); } catch (Exception exception) { Log.e("MyAmplifyApp", "Upload failed", exception); }
RxProgressAwareSingleOperation<StorageUploadFileResult> upload = RxAmplify.Storage.uploadFile("ExampleKey", exampleFile);
upload .observeResult() .subscribe( result -> Log.i("MyAmplifyApp", "Successfully uploaded: " + result.getKey()), error -> Log.e("MyAmplifyApp", "Upload failed", error) );}
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: