【问题标题】:Upload multi images to firestore using flutter and get it's download URLs and save all of URLs to firebase使用flutter将多张图片上传到firestore并获取它的下载URL并将所有URL保存到firebase
【发布时间】:2020-04-14 16:55:12
【问题描述】:

我有一个要上传图像的表单,当用户尝试按下“提交”按钮时,我正在尝试将图像列表上传到 firestore 并获取其所有 URL,然后将表单提交到“x”在firebase中收集,但在上传图像并获取它的URL之前完成了“x”搭配的写作。

我认为 (async,await) 有问题。

感谢您帮助我。

List<File> imagePaths= new List() ;
List<String> imageURL= new List() ;

Future<FirebaseUser> getUser() async {
    return await _auth.currentUser();
}

Future<void> uploadPic(File _image) async {

    String fileName = basename(_image.path);
    StorageReference firebaseStorageRef = 
    FirebaseStorage.instance.ref().child(Random().nextInt(10000).toString()+fileName);
    StorageUploadTask uploadTask = firebaseStorageRef.putFile(_image);
    var downloadURL = await(await uploadTask.onComplete).ref.getDownloadURL();
    var url =downloadURL.toString();
    imageURL.add(url); // imageURL is a global list that suppose to contain images URLs
    print("\n ---------------------------\n downloadURL :"+ url);
    print("\n ---------------------------\n imageURL :"+ imageURL.toString());

  }


Submit(BuildContext context)   {
    //imagePaths is list of file 
    imagePaths.add(Front_image);
    imagePaths.add(Back_image);

    imagePaths.forEach((x)  => {
       uploadPic(x)
    });


    getUser().then((user) {

      crudObj.addNew({
        'uid': user.uid,
        'name': name,
        'images':imageURL,
      }).then((result) {
        Navigator.pop(context);

      }).catchError((e) {
        print(e);
      });
    });

  }

【问题讨论】:

    标签: firebase flutter async-await firebase-storage


    【解决方案1】:

    只有在上传任务完成后,您才应该调用 Submit。我建议实施这样的事情:

    Stream uploadImageToFirebaseStorage(File image, String fullPath) {
      final StorageReference firebaseStorageRef =
          FirebaseStorage.instance.ref().child(fullPath);
      StorageUploadTask task = firebaseStorageRef.putFile(image);
    
      return task.events;
    }
    

    然后监听这个 Stream 然后才提交:

    uploadImageToFirebaseStorage(
      image, 'path/imagename.jpg'
    ).listen((data) async {
      StorageTaskEvent event = data;
      if (data.type == StorageTaskEventType.success) {
        String downloadUrl = await event.snapshot.ref.getDownloadURL();
        await Submit(title, imageUrl: downloadUrl);
        return true;
      }
      if (data.type == StorageTaskEventType.failure) return false;
    });
    

    请注意,我没有重写你的代码,我正在分享一个可能的实现。

    【讨论】:

    • 但是我有多张图片而不是一张图片
    • 那你需要为每张图片运行代码,有什么问题?
    • 在您的解决方案中,我将把表单作为图像数量。一旦所有图片网址准备就绪,我需要提交表单
    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2020-11-19
    • 1970-01-01
    • 2021-12-27
    • 2021-03-14
    • 2020-12-10
    • 2020-12-05
    相关资源
    最近更新 更多