skip to Main Content

I’ve this Button to select images:

IconButton(
            onPressed: () async {
              final results = await FilePicker.platform.pickFiles(
                allowMultiple: true,
                type: FileType.custom,
                allowedExtensions: ['png', 'jpg'],
              );
              if (results == null) {
                ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                    content: Text("No Image selected")
                ),
                );
                return null;
              }

              final path = results.files.single.path!;
              final fileName = results.files.single.name;
              final docID = widget.docID;

                storage
              .uploadFile(path, fileName, docID)
              .then((value) => print('Done'));
            },

          icon: Icon(),
        ),

…then the upload function:

Future<void> uploadFile(

String filePath,
String fileName,
String docID,
) async {
  File file = File(filePath);
  try {

    await storage.ref('images/test/$docID/$fileName').putFile(file);
  } on firebase_core.FirebaseException catch (e) {
    print(e);
  }
}

This works with single images, now i want to select and upload multiple files. The selecting works already, but how can i upload them?

I tried to save the files as a list, but have no idea how to continue:
List files = results.paths.map((path) => File(path!)).toList();

2

Answers


  1.     IconButton(
                    onPressed: () async {
                      final results = await FilePicker.platform.pickFiles(
                        allowMultiple: true,
                        type: FileType.custom,
                        allowedExtensions: ['png', 'jpg'],
                      );
                      if (results == null) {
                        ScaffoldMessenger.of(context).showSnackBar(
                        const SnackBar(
                            content: Text("No Image selected")
                        ),
                        );
                        return null;
                      }
                      final List<String> filePaths = results.paths!;
                      for (String path in filePaths) {
                      final fileName = path.split('/').last;
                      final docID = widget.docID;
    
                     await storage.uploadFile(path, fileName, docID);
        }
      },
        
                  icon: Icon(),
                ),
    
    Login or Signup to reply.
  2. You can just run the uploadFile multiple times, just make sure to use Future.wait() so that the uploads run in parallel.

    Future<List<String>> uploadFiles(List<File> _images) async {
      var imageUrls = await Future.wait(_images.map((_image) => 
      uploadFile(_image)));
      return imageUrls;
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search