Upload files
Upload File
To upload to S3 from a file, specify the key and the local file to be uploaded. A file can be created locally, or retrieved from the user's device using a package such as image_picker or file_picker.
Upload a local file
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 file7 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 S315 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}
Upload file with Flutter file picker packages
Make sure to follow the setup instructions on the image_picker homepage.
1import 'dart:io';2
3import 'package:image_picker/image_picker.dart';4
5final picker = ImagePicker();6
7Future<void> uploadImage() async {8 // Select image from user's gallery9 final pickedFile = await picker.pickImage(source: ImageSource.gallery);10
11 if (pickedFile == null) {12 safePrint('No image selected');13 return;14 }15
16 // Upload image with the current time as the key17 final key = DateTime.now().toString();18 final file = File(pickedFile.path);19 try {20 final result = await Amplify.Storage.uploadFile(21 local: file,22 key: key,23 onProgress: (progress) {24 safePrint('Fraction completed: ${progress.getFractionCompleted()}');25 },26 );27 safePrint('Successfully uploaded image: ${result.key}');28 } on StorageException catch (e) {29 safePrint('Error uploading image: $e');30 }31}
Upload Options
You may attach metadata while uploading data or a file via specifying metadata
in options.
1await Amplify.Storage.uploadFile(2 key: 'file',3 local: File('path/to/file'),4 options: S3UploadFileOptions(5 metadata: const {6 'project': 'ExampleProject',7 },8 ),9);
In S3 console, you should see the metadata attached to your file. You can learn more about the different access levels in File access levels.
Multipart upload
Amplify will automatically perform a S3 multipart upload for files larger than 5MB. For more information about S3's multipart upload support, see Uploading and copying objects using multipart upload.