将多张图片上传到Firebase,然后将图片网址保存到Firestore [英] Upload multiple images to firebase then save image url to firestore

查看:35
本文介绍了将多张图片上传到Firebase,然后将图片网址保存到Firestore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以协助我修改代码,以便它等待上传完成然后将图像URL保存到Firestore吗?我是异步和等待的新手,似乎无法弄清楚.即使我在 Promise.all(promises).then():

Can someone assist me with revising the code so it will wait for the upload to finish then save the image urls to firestore? I'm new to async and await and can't seem to figure it out. The fileDownloadUrl is still empty even if I do the saving to firestore inside the Promise.all(promises).then():

cxonst promises = [];
const fileDownloadUrl = [];

pictures.forEach(file => {
    const uploadTask = 
    firebase
    .storage()
    .ref()
    .child(`img/upl/${file.data.name}`)
    .put(file.uploadTask);
    
    promises.push(uploadTask);

    uploadTask.on(
        
        firebase.storage.TaskEvent.STATE_CHANGED,
        snapshot => {
            const progress = Math.round((snapshot.bytesTransferred / 
                 snapshot.totalBytes) * 100);
            
            if (snapshot.state === firebase.storage.TaskState.RUNNING) {
                console.log(`Progress: ${progress}%`);
            }
        },
        error => console.log(error.code),
        async () => {
            const downloadURL = await 
            uploadTask.snapshot.ref.getDownloadURL();
            fileDownloadUrl.push(downloadURL);
            }
        );
    });

    Promise.all(promises)
    .then(() => {
        db
        .collection("properties")
        .add({
            timestamp: firebase.firestore.FieldValue.serverTimestamp(),
            title: title,
            description: description,
            pictures: fileDownloadUrl,
            user: user.uid
        })
    })
    .catch(err => console.log(err));

推荐答案

在等待 put 调用的承诺完成时,您将使用 uploadTask.on()确定下载URL.由于此 on 不在承诺中,因此不能保证它们是同步的.

While you are waiting for the promises of the put calls to complete, you're then using the uploadTask.on() to determine the download URL. Since this on is not part of the promise, there is no guarantee they're in sync.

一种更简单有效的方法应该是:

A simpler and working approach should be:

const promises = pictures.map(file => {
  const ref = firebase.storage().ref().child(`img/upl/${file.data.name}`);
  return ref
    .put(file.uploadTask)
    .then(() => ref.getDownloadURL())
});

Promise.all(promises)
.then((fileDownloadUrls) => {
    db
    .collection("properties")
    .add({
        timestamp: firebase.firestore.FieldValue.serverTimestamp(),
        title: title,
        description: description,
        pictures: fileDownloadUrls,
        user: user.uid
    })
})
.catch(err => console.log(err));

这篇关于将多张图片上传到Firebase,然后将图片网址保存到Firestore的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆