【问题标题】:waiting array of urls after uploading images to firebase storage and then stroing it again to firestore将图像上传到firebase存储后等待url数组,然后再次将其发送到firestore
【发布时间】:2021-07-05 22:14:03
【问题描述】:
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。非常感谢您对如何做到这一点的意见?

【问题讨论】:

    标签: reactjs firebase google-cloud-firestore


    【解决方案1】:

    您可以创建一个接收reffile 并返回downloadURL 的函数。通过使用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);
    };
    
    

    【讨论】:

      猜你喜欢
      • 2021-04-28
      • 2021-03-19
      • 2019-07-24
      • 1970-01-01
      • 1970-01-01
      • 2020-04-21
      • 2018-12-21
      • 1970-01-01
      • 2018-01-24
      相关资源
      最近更新 更多