首页 > 解决方案 > 将图像上传到firebase存储然后再次将其传输到firestore后等待url数组

问题描述

const sendImageToFirebase = (e) => {
    const promises = []
    const urlsArray = []
    // productimage is an array of image files
    productImage.forEach((image, i) => {
        var storageRef = firebase.storage().ref();
        var uploadTask = storageRef.child(`${userDetailsFirebase.uid}/` + Math.random()).put(image);
        promises.push(uploadTask.on('state_changed',
            (snapshot) => {
            },
            (error) => {
                console.log("error");
            },
            async () => {
                const downloadurl = await uploadTask.snapshot.ref.getDownloadURL()
                urlsArray.push(downloadurl)
            }
        ))
    })
    Promise.all(promises).then(res => {
        db.collection("products").doc(idGeneratedforProduct).set(
            {
                imageURL: urlsArray, //array of image urls
            },
        ).then(e => {
        }).catch(error => console.log("Error while sendig items to Firebase"))
    })
} 

我想将多个图像上传到 Firebase 存储。这里sendImagToFirebase是reactJs中的普通函数,productimage是图片文件数组。我想等待每个图像文件的 URL,然后将它们作为数组存储到 firestore。我将不胜感激您对如何做到这一点的意见?

标签: reactjsfirebasegoogle-cloud-firestore

解决方案


您可以创建一个函数来接收reffile并返回downloadURL. 通过使用 a 为每个文件调用它,Promise.all您将获得downloadURLs 数组:

const uploadFileAndGetDownloadURL = async (ref, file) => {
  const snap = await ref.put(file);
  const downloadURL = await snap.ref.getDownloadURL();

  return downloadURL;
};

const sendImageToFirebase = async (e) => {
  const promises = [];
  productImage.forEach((image, i) => {
    var storageRef = firebase.storage().ref();
    var ref = storageRef.child(`${userDetailsFirebase.uid}/` + Math.random());
    promises.push(uploadFileAndGetDownloadURL(ref, image));
  });

  //Your array with the urls
  const urlsArray = await Promise.all(promises);
};


推荐阅读