如何一次将多个文件上传到Firebase存储? [英] How can i upload multiple files to firebase storage at once?

查看:72
本文介绍了如何一次将多个文件上传到Firebase存储?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在ionic+angularfire2中创建一个应用程序,我想将一些图像上传到firebase storage,但是我想一次全部上传,或者至少在(x > 1)时一次上传.

I am creating an app in ionic+angularfire2 and i want to upload some images to firebase storage, but i want to upload them all at once or at least X at the time (x > 1).

现在我像这样上传它们

async imageUpload(name, file) {
    // The storage path
    const path = name;
    // The main task
    let img = 'data:image/jpg;base64,' + file;
    return this.task = this.afStorage.ref('/').child(name).putString(img, 'data_url').then((snapshot) => {
    console.log(snapshot)
}).catch((err) => {
    console.log(err);
});

}

然后我循环遍历包含文件的数组

then i just loop trought the array that contains the files

let newDocId = this.afStore.createId();
for (var i = 0; i < this.lotProvider.uploadFoto.b64Image.length; i++) {
    let name = 'feriaganadera/'+newDocId +'/'+ (+ new Date()) + "-image_foto_jpeg_" + i + ".jpeg";
    this.imageUpload(name, this.lotProvider.uploadFoto.b64Image[i]);
}

可以正常工作,文件已上传,但必须等待文件上传下一个文件.

that work, the files are uploaded, but it has to wait for a file to upload the next one.

如何调用异步函数?因此imageUpload不必等待图像.

How can i call the functions asynchronous? so imageUpload does not have to wait for the images.

推荐答案

尝试Promise.all,首先将您的imageUpload函数修改为此以返回承诺:

Try with Promise.all, first modify your imageUpload function to this to return a promise:

imageUpload(name, file) {

    return new Promise((resolve, reject) =>{
        // The storage path
        const path = name;
        // The main task
        let img = 'data:image/jpg;base64,' + file;
        this.task = this.afStorage.ref('/').child(name).putString(img, 'data_url').then((snapshot) => {
            console.log(snapshot);
            resolve(snapshot);
        }).catch((err) => {
            console.log(err);
            reject(err);
        });
    });
}

然后将Promise.all与base64字符串数组一起使用:

And use Promise.all with your array of base64 strings:

Promise.all(this.lotProvider.uploadFoto.b64Image.map(async (img) => {
    console.log(img);
    const content = await this.imageUpload('name','file');
    return content;
}))
.then(values => { 
    console.log(values);
})
.catch((err) => {
    console.log(err);
});

这将在创建Promise时(即在迭代数组时)启动"您的上传.

That'll 'launch' your uploads at the time the promises are created, which is as the array is being iterated.

这篇关于如何一次将多个文件上传到Firebase存储?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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