本文介绍了Flutter上载一批图像并获取所有这些URL以存储在Firestore中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将n张照片上传到Firebase存储并将这些URL保存在Firestore中的数组中,但是我无法获得 downloadURL()或者我不知道在哪里找到它。我检查了其他答案,但是这些答案是针对单个文件的,我试图上传一批并将URL一起存储,而不是上传并存储到Firestore的URL,依此类推,以此类推...

I'm trying to upload n number of photos to Firebase Storage and save those URLs in an array inside Firestore, but I am not able to get the downloadURL() or I do not know where to find it rather. I've checked other answers but those were for single files, I'm trying to upload a batch and store the URLs together instead of uploading on and storing the URL to Firestore and so on and so forth...

代码:

_uploadImages(String userID, String productID, List<File> images, Function onSuccess(List<String> imageURLs), Function onFailure(String e)) {
    List<String> imageURLs = [];
    int uploadCount = 0;

    StorageReference storeRef = FirebaseStorage.instance.ref().child('Products').child(userID).child(productID).child(uploadCount);
    StorageMetadata metaData = StorageMetadata(contentType: 'image/png');

    images.forEach((image) {
      storeRef.putFile(image, metaData).onComplete.then((snapshot) {
        STUCK AT THIS POINT SINCE THE SNAPSHOT DOESN'T SHOW THE URL OPTION...
        //imageURLs.add(snapshot. )
        uploadCount++;

        if (uploadCount == images.length) {
          onSuccess(imageURLs);
        }
      });
    });
  }


推荐答案

您可以使用此方法将多个文件上传到Firebase存储,其中 List< Asset> 资产是您的 List< File> 文件。

You could use this method for multiple file upload to firebase storage where List<Asset> assets are your List<File> files.

Future<List<String>> uploadImage(
      {@required String fileName, @required List<Asset> assets}) async {
    List<String> uploadUrls = [];

    await Future.wait(assets.map((Asset asset) async {
      ByteData byteData = await asset.requestOriginal();
      List<int> imageData = byteData.buffer.asUint8List();

      StorageReference reference = FirebaseStorage.instance.ref().child(fileName);
      StorageUploadTask uploadTask = reference.putData(imageData);
      StorageTaskSnapshot storageTaskSnapshot;

      // Release the image data
      asset.releaseOriginal();

      StorageTaskSnapshot snapshot = await uploadTask.onComplete;
      if (snapshot.error == null) {
        storageTaskSnapshot = snapshot;
        final String downloadUrl = await storageTaskSnapshot.ref.getDownloadURL();
        uploadUrls.add(downloadUrl);

        print('Upload success');
      } else {
        print('Error from image repo ${snapshot.error.toString()}');
        throw ('This file is not an image');
      }
    }), eagerError: true, cleanUp: (_) {
     print('eager cleaned up');
    });

    return uploadUrls;
}

这篇关于Flutter上载一批图像并获取所有这些URL以存储在Firestore中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-01 21:33