Flutter上传批量图像并获取要存储在Firestore中的所有URL

问题描述 投票:1回答:2

我正在尝试将大量照片上传到Firebase存储并将这些网址保存在Firestore内的数组中,但我无法获取downloadURL()或者我不知道在哪里找到它。我已经检查了其他答案,但那些是针对单个文件的,我正在尝试上传批处理并将URL存储在一起而不是上传并将URL存储到Firestore等等......

码:

_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 dart flutter google-cloud-firestore firebase-storage
2个回答
1
投票

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

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;
}

0
投票

试试这个(在onComplete里面):

storeRef.getDownloadURL() 
© www.soinside.com 2019 - 2024. All rights reserved.