首页 > 解决方案 > Flutter 上传一批图像并获取所有这些 URL 以存储在 Firestore 中

问题描述

我正在尝试将 n 张照片上传到 Firebase 存储并将这些 URL 保存在 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);
        }
      });
    });
  }

标签: firebasedartfluttergoogle-cloud-firestorefirebase-storage

解决方案


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

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

推荐阅读