【问题标题】:How can i upload multiple files to firebase storage at once?如何一次将多个文件上传到 Firebase 存储?
【发布时间】:2018-10-17 14:57:49
【问题描述】:

我正在ionic+angularfire2 中创建一个应用程序,我想将一些图像上传到firebase storage,但我想一次上传它们,或者至少在X 上传它们(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);
});

}

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

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]);
}

那行,文件上传了,但它必须等待一个文件才能上传下一个。

如何异步调用函数?所以imageUpload 不必等待图像。

【问题讨论】:

    标签: angular firebase ionic3 firebase-storage


    【解决方案1】:

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

    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 字符串数组一起使用:

    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 时“启动”您的上传,也就是迭代数组时。

    【讨论】:

      猜你喜欢
      • 2020-05-17
      • 2019-08-18
      • 2020-04-08
      • 2016-11-05
      • 2018-06-21
      • 2019-02-10
      • 2017-05-31
      • 2019-12-12
      • 2021-04-07
      相关资源
      最近更新 更多