Home > Mobile >  Get the download URLs of multiple files in firebase storage
Get the download URLs of multiple files in firebase storage

Time:09-21

So after searching stack overflow for hours, I give up, I can't find a solution that solves my problem, I'm creating an application where users can send multiple photos to each other! The way it works is a user selects the photos from the gallery, it saves the paths to a LIST and it uploads them to firebase storage using a for loop based on the index of that list. Code

        for(int i = 0; i < filePaths.length; i  ) {
      List<String> imageLinks = [];
      var imageStorageRef = storage.child(
          'SentImages/${widget.chatRoomID}/$path/${uuid.v1()}');
      imageStorageRef.putFile(filePaths[i]);

The problem is I need to acquire the download URL of the files in firebase storage and save them in a list but no solution works and each time the list comes out as empty. Full code

    Uuid uuid = const Uuid();
Future<void> selectImages() async {
  String path = uuid.v4();
  List<XFile>? selectedImages = await picker.pickMultiImage();
  if (selectedImages != null) {
    List<File> filePaths = [];
    for(int i = 0; i < selectedImages.length; i  ){
      filePaths.add(File(selectedImages[i].path));
    }
    for(int i = 0; i < filePaths.length; i  ) {
      List<String> imageLinks = [];
      var imageStorageRef = storage.child(
          'SentImages/${widget.chatRoomID}/$path/${uuid.v1()}');
      imageStorageRef.putFile(filePaths[i]);
      final listData = await imageStorageRef.listAll();
      Future.wait(listData.items.map((e) async {
        await e.getDownloadURL().then((value) {
          imageLinks.add(value);
          print(imageLinks);
        });
      }));
      print(imageLinks);
    }

How do I make it acquire each download link as the loop goes or even get the download links of all the files in that folder directly from firebase storage! Thank you.

CodePudding user response:

I think you need to upload photos file by file and store the download url in the list , try this

 static Future<List<String>> uploadFiles(List<File> _images) async {
   var imageUrls = await Future.wait(_images.map((_image) =>uploadFile(_image)));
   print(imageUrls);
   return imageUrls;
 }

 static Future<String> uploadFile(File _image,) async {
   final storageReference = FirebaseStorage.instance.ref()
    .child('images/${_image.path}');
  UploadTask uploadTask = storageReference.putFile(_image);
  await uploadTask.whenComplete((){ });
  return  await storageReference.getDownloadURL();
}

and at last you can call like this

 List<String> urls = await uploadFiles("yourListOfFiles");
  • Related