将多个Xfile上传到Firebase存储

发布于 2025-02-13 09:10:30 字数 1602 浏览 0 评论 0原文

我正在尝试将多个(最大5)Xfiles Images(Image_picker库)上传到firebase存储。当前,它仅上传一个使用以下方法的上传:

Future<void> addProduct({
BuildContext? ctx,
String? proName,
String? productDescription,
double? count,
double? price,
required List<XFile> images
}) async {
try {
  var imageUrls = await Future.wait(images.map((_image) =>
    uploadFile(_image)));

  await firestore
      .collection(outletsCollection)
      .doc(_currentUserOutletId)
      .set({
    products: FieldValue.arrayUnion([
      {
        productId: Uuid().v4(),
        productName: proName,
        prodDesc: productDescription,
        countInStock: count,
        productPrice: price,
        productImg: FieldValue.arrayUnion([imageUrls]),
      }
    ]),
  });
} catch (err) {
  String errMsg = "error blahblah";
  errorDialog(ctx!, errMsg);
}
notifyListeners();
}

对于我尝试使用images.foreach()而不是.map()的uploadfile方法,但它给了我void类型错误。 uploadfile方法:

Future<String> uploadFile(XFile _image) async {

var storageReference = storage
    .ref()
    .child('product_images')
    .child(_currentUserOutletId!)
    .child(Uuid().v4());

final metadata = SettableMetadata(
  contentType: 'image/jpeg',
  customMetadata: {'picked-file-path': _image.path},
);

if (kIsWeb) {
  await storageReference.putData(await _image.readAsBytes(), metadata);
} else {
  await storageReference.putFile(io.File(_image.path), metadata);
}
return await storageReference.getDownloadURL();

}

因此,最后,只有一个图像被上传,并且AddProduct()不会将产品添加到Firestore数据库中。登录Android Studio一无所获。我找不到可以与Xfile一起使用的方法。帮助非常感谢!

I am trying to upload multiple (max 5) xfiles images (image_picker library) to firebase storage. currently, it uploads only one with the below method:

Future<void> addProduct({
BuildContext? ctx,
String? proName,
String? productDescription,
double? count,
double? price,
required List<XFile> images
}) async {
try {
  var imageUrls = await Future.wait(images.map((_image) =>
    uploadFile(_image)));

  await firestore
      .collection(outletsCollection)
      .doc(_currentUserOutletId)
      .set({
    products: FieldValue.arrayUnion([
      {
        productId: Uuid().v4(),
        productName: proName,
        prodDesc: productDescription,
        countInStock: count,
        productPrice: price,
        productImg: FieldValue.arrayUnion([imageUrls]),
      }
    ]),
  });
} catch (err) {
  String errMsg = "error blahblah";
  errorDialog(ctx!, errMsg);
}
notifyListeners();
}

for the uploadFile method i tried using images.forEach() instead of .map(), but it gave me void type error. uploadFile method:

Future<String> uploadFile(XFile _image) async {

var storageReference = storage
    .ref()
    .child('product_images')
    .child(_currentUserOutletId!)
    .child(Uuid().v4());

final metadata = SettableMetadata(
  contentType: 'image/jpeg',
  customMetadata: {'picked-file-path': _image.path},
);

if (kIsWeb) {
  await storageReference.putData(await _image.readAsBytes(), metadata);
} else {
  await storageReference.putFile(io.File(_image.path), metadata);
}
return await storageReference.getDownloadURL();

}

so, at the end only one image is uploaded and addProduct() does not add product to firestore database. log in android studio returns nothing. I couldn't find a method that would work with the xfile. help appreciated very much!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

我恋#小黄人 2025-02-20 09:10:30
List<XFile> _imageFileList;

try{
final pickedFile = await _picker.pickMultiImage();
setState(() {
            _imageFileList = pickedFile;
     _imageFileList.forEach((element) async {
    firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;
                var date = DateTime.now().millisecondsSinceEpoch;
                try {
                  setState(() {
                    _loading = true;
                  });
                  firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance.ref('uploads/photos/'+date.toString()+'_image.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));

                  await storage.ref('uploads/file-to-upload.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
                  firebase_storage.TaskSnapshot  downloadUrl = (await task);

                  String url = (await downloadUrl.ref.getDownloadURL());
                  // print(url.toString());
                } on FirebaseException catch (e) {
                  // e.g, e.code == 'canceled'
                  setState(() {
                    _loading = false;
                  });
                }
    });

使用Image_picker插件尝试使用这种方式。您可以在上传图像后获取URL,然后将其包含在数据中。

List<XFile> _imageFileList;

try{
final pickedFile = await _picker.pickMultiImage();
setState(() {
            _imageFileList = pickedFile;
     _imageFileList.forEach((element) async {
    firebase_storage.FirebaseStorage storage = firebase_storage.FirebaseStorage.instance;
                var date = DateTime.now().millisecondsSinceEpoch;
                try {
                  setState(() {
                    _loading = true;
                  });
                  firebase_storage.UploadTask task = firebase_storage.FirebaseStorage.instance.ref('uploads/photos/'+date.toString()+'_image.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));

                  await storage.ref('uploads/file-to-upload.png').putData(await element.readAsBytes(), SettableMetadata(contentType: 'image/jpeg'));
                  firebase_storage.TaskSnapshot  downloadUrl = (await task);

                  String url = (await downloadUrl.ref.getDownloadURL());
                  // print(url.toString());
                } on FirebaseException catch (e) {
                  // e.g, e.code == 'canceled'
                  setState(() {
                    _loading = false;
                  });
                }
    });

try this way using image_picker plugin. You can get url after image upload and you have yo it in your data.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文