Page updated Jan 16, 2024

Set up Amplify Storage

Amplify Flutter v0 is now in Maintenance Mode until July 19th, 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 v0.

Please use the latest version (v1) of Amplify Flutter to get started.

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

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.

Web and desktop support for the Amplify Flutter Storage category is now in developer preview! See the documentation for project setup for more information about getting started.

The developer preview release is not intended for production usage.

Goal

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

Prerequisites

  • A Flutter application targeting Flutter SDK >= 2.10.0 (stable version) with Amplify libraries integrated
    • An iOS configuration targeting at least iOS 11.0
    • An Android configuration targeting at least Android API level 21 (Android 5.0) or above
    • For a full example please follow the project setup walkthrough

You can see an example Amplify Storage + Flutter application here.

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.dart 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

Add the following dependency to your app's pubspec.yaml along with others you added above in Prerequisites:

1environment:
2 sdk: ">=2.15.0 <3.0.0"
3
4dependencies:
5 amplify_auth_cognito: ^0.6.0
6 amplify_flutter: ^0.6.0
7 amplify_storage_s3: ^0.6.0
8 flutter:
9 sdk: flutter

Initialize Amplify Storage

To initialize the Amplify Auth and Storage categories, call Amplify.addPlugin() for each plugin or pass all the plugins in Amplify.addPlugins(). To complete initialization, call Amplify.configure().

Your code should look like this:

1import 'package:amplify_auth_cognito/amplify_auth_cognito.dart';
2import 'package:amplify_flutter/amplify_flutter.dart';
3import 'package:amplify_storage_s3/amplify_storage_s3.dart';
4import 'package:flutter/material.dart';
5
6import 'amplifyconfiguration.dart';
7
8Future<void> _configureAmplify() async {
9 try {
10 final auth = AmplifyAuthCognito();
11 final storage = AmplifyStorageS3();
12 await Amplify.addPlugins([auth, storage]);
13
14 // call Amplify.configure to use the initialized categories in your app
15 await Amplify.configure(amplifyconfig);
16 } on Exception catch (e) {
17 safePrint('An error occurred configuring Amplify: $e');
18 }
19}
20
21Future<void> main() async {
22 WidgetsFlutterBinding.ensureInitialized();
23 await _configureAmplify();
24 runApp(const MyApp());
25}
26
27class MyApp extends StatefulWidget {
28 const MyApp({Key? key}) : super(key: key);
29
30 // ...
31}

Uploading data to your bucket

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

Here you use the path_provider package to get a directory where you can create a temporary file for uploading.

1import 'dart:io';
2
3import 'package:path_provider/path_provider.dart';
4
5Future<void> createAndUploadFile() async {
6 // Create a dummy file
7 const exampleString = 'Example file contents';
8 final tempDir = await getTemporaryDirectory();
9
10 final exampleFile = File('${tempDir.path}/example.txt');
11 await exampleFile.create();
12 await exampleFile.writeAsString(exampleString);
13
14 // Upload the file to S3
15 try {
16 final result = await Amplify.Storage.uploadFile(
17 local: exampleFile,
18 key: 'ExampleKey',
19 onProgress: (progress) {
20 safePrint('Fraction completed: ${progress.getFractionCompleted()}');
21 },
22 );
23 safePrint('Successfully uploaded file: ${result.key}');
24 } on StorageException catch (e) {
25 safePrint('Error uploading file: $e');
26 } finally {
27 await exampleFile.delete();
28 }
29}

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: