Download files
There are three ways of getting data that was previously uploaded:
Download File
You can download file to a local directory using Amplify.Storage.downloadFile
.
You can use the path_provider package to create a local file in the user's documents directory where you can store the downloaded data.
1import 'package:path_provider/path_provider.dart';2
3Future<void> downloadToLocalFile(String key) async {4 final documentsDir = await getApplicationDocumentsDirectory();5 final filepath = documentsDir.path + '/example.txt';6 try {7 final result = await Amplify.Storage.downloadFile(8 key: key,9 localFile: AWSFile.fromPath(filepath),10 onProgress: (progress) {11 safePrint('Fraction completed: ${progress.fractionCompleted}');12 },13 ).result;14
15 safePrint('Downloaded file is located at: ${result.localFile.path}');16 } on StorageException catch (e) {17 safePrint(e.message);18 }19}
Download data
You can download a file to in-memory buffer with Amplify.Storage.downloadData
:
1Future<void> downloadToMemory(String key) async {2 try {3 final result = await Amplify.Storage.downloadData(4 key: key,5 onProgress: (progress) {6 safePrint('Fraction completed: ${progress.fractionCompleted}');7 },8 ).result;9
10 safePrint('Downloaded data: ${result.bytes}');11 } on StorageException catch (e) {12 safePrint(e.message);13 }14}
Generate a download URL
You can get a downloadable URL for the file in storage by its key and access level.
When creating a downloadable URL, you can choose to check if the file exists by setting validateObjectExistence
to
true
in S3GetUrlPluginOptions
. If the file is inaccessible or does not exist, a StorageException
is thrown.
This allows you to check if an object exists during generating the presigned URL, which you can then use to download
that object.
1Future<String> getDownloadUrl({2 required String key,3 required StorageAccessLevel accessLevel,4}) async {5 try {6 final result = await Amplify.Storage.getUrl(7 key: key,8 options: const StorageGetUrlOptions(9 accessLevel: accessLevel,10 pluginOptions: S3GetUrlPluginOptions(11 validateObjectExistence: true,12 expiresIn: Duration(days: 1),13 ),14 ),15 ).result;16 return result.url.toString();17 } on StorageException catch (e) {18 safePrint('Could not get a downloadable URL: ${e.message}');19 rethrow;20 }21}