firebase - 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);
}
});
});
}
解决方案
您可以使用此方法将多个文件上传到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;
}
推荐阅读
- c# - 在给定 Microsoft.Odata.Edm.IEdmModel 的情况下,如何确定绑定操作(函数或操作)所属的 EntitySet?
- google-apps-script - 应用程序脚本 - 在现有文件夹中创建新的谷歌文档
- reactjs - 如何使用反应虚拟化创建包含大量数据并支持扩展行和固定列的复杂表?
- ios - 一个 Xcode 文件中的多个主故事板
- asp.net-mvc - 使用 POSTMAN 对 OPENID 服务器进行身份验证
- php - 如何通过 Stripe PHP 和 webhook 使用 good 事件,比较收到的付款数量并取消订阅
- reporting-services - textbox4 的值表达式直接引用字段
- node.js - 猫鼬(检查并保存如果新)
- java - 如何知道 JVM 因 Segfault 而崩溃的原因?
- asp.net-mvc - '值不能为空。参数名称:ViewStart.cshtml 上的 virtualPath'