flutteramazon-web-servicesdownloadaws-amplifyflutter-aws-amplify

How can I download images by url faster in AWS Amplify using Flutter?


I'm constantly getting this message in Flutter: 'Connection closed before full header was received', when calling to create a download url for an image from storage.

It takes very long for the images to download, as the url needs to be regenerated, because the tokens expire in a short amount of time.

I'm wondering if there's faster way to do this, especially to download multiple images quickly.

final images = await Amplify.Storage.getUrl(key: element.groupIconUrl);

Solution

  • AWS Amplify DA here 👋

    If you want to download the file with key, you can use the downloadFile function instead of getUrl

    I don't know which version of the library that you are working with but with the latest stable version of the AWS Amplify, you can download a local copy of the file by doing the following by using path_provider package:

    import 'dart:io';
    import 'package:path_provider/path_provider.dart';
    
    Future<void> downloadFile() async {
      final documentsDir = await getApplicationDocumentsDirectory();
      final filepath = documentsDir.path + '/example.txt';
      final file = File(filepath);
    
      try {
        final result = await Amplify.Storage.downloadFile(
          key: element.groupIconUrl,
          local: file,
          onProgress: (progress) {
            safePrint('Fraction completed: ${progress.getFractionCompleted()}');
          },
        );
        final contents = result.file.readAsStringSync();
        // Or you can reference the file that is created above
        // final contents = file.readAsStringSync();
        safePrint('Downloaded contents: $contents');
      } on StorageException catch (e) {
        safePrint('Error downloading file: $e');
      }
    }
    

    For more information, you can check the official documentation here.

    Let me know if you have any further questions!

    EDIT: Question: How to generate URL for images?

    The AWS Amplify generates a signed URL for each user according to the level of access that they have. That is why you can (also should) not generate a URL and let it be. You can define the expiration date for it.

    How I do it in my sample app is as the following. Each time when I have see the image in the screen, then I call for getting the URL. Also I cache the image so when I come back I can keep the previous reference to it.

    So my answer is, do not fetch all the image urls, only get them when you use them.