将图像阵列上传到Firebase存储

时间:2020-01-09 10:21:59

标签: arrays node.js firebase react-native firebase-storage

我正在尝试将一系列图像上传到Firebase存储。我已经为单个图像上传编写了一个函数,并且该函数可以完美运行,但是我似乎无法全神贯注于如何实现图像阵列上传。有人能指出我正确的方向吗?下面是我的示例,我只保留了相关部分

        uploadAsync = async uri => {
          const user = Firebase.auth.currentUser.uid;
          const path = `users/${user}/images/${Math.round(
                  Math.random() * 1000000000
              )}.jpg`;

          return new Promise(async (res, rej) => {
            const response = await fetch(uri);
            const file = await response.blob();

            const upload = Firebase.storage().ref(path).put(file);

            upload.on(
              'state_changed',
              snapshot => {},
              err => {
                rej(err);
              },
              async () => {
                const url = await upload.snapshot.ref.getDownloadURL();
                res(url);
              }
            );
          });
        };

        updateImage = async ({ image }) => {
          const user = Firebase.auth.currentUser.uid;
          for (let i = 0; i < image.length; i++) {
            const file = image[i].image;
            const remoteUri = await this.uploadAsync(file);
            const firestoreRef = firebase.firestore().collection('Images').doc(user);
            firestoreRef.set({
              image: [remoteUri]
            });
          }
        }

2 个答案:

答案 0 :(得分:1)

您可以使用Promise.all()。如文档中所述:

Promise.all()方法返回一个Promise,该Promise在以下情况下满足 通过迭代的所有诺言都已兑现

.....

返回的promise由一个数组实现,该数组包含作为参数传递的所有iterable值(也包括非承诺值)。

由于您的updateImage()函数是异步函数,因此您可以将基于{{1生成的”对该函数的一系列“调用”(上述的“可迭代”)传递给Promise.all() }}是imageArray个对象的数组(与传递给image函数的image对象完全相同)。

因此,您可以执行以下操作:

updateImage()

或在异步函数中:

const updateImageArray = async (imageArray) => {
  return Promise.all(imageArray.map(item => updateImage(item)));
}

const imageArray = [....];

updateImageArray(imageArray).then(urls => {
    urls.forEach(element => {
        console.log(element);
    });
})

答案 1 :(得分:0)

基本上,这里的问题是您需要自己上传每个图像。不存在“捆绑”上传或类似内容。

常规方法

解决此问题的基本方法是循环遍历数组(此处为图像imgArr数组)并分别上传每个项目。
这样的功能如下所示:

for (i = 0; i < imgArr.length; i++) {
    this.updateImage(imgArr[i]);
}

或使用forEach方法:

imgArr.forEach((img) => {
    this.updateImage(img);
}

记住 : 原始代码中提供了this.updateImage函数。

在异步功能(例如上载,数据获取或其他这种方法)不起作用的情况下。这是由JS的实现引起的,事实上,for(Each)循环内的操作无法等待。

该解决方案随附 asyncForEach 。 asyncForEach函数执行异步任务(上传图像)并等待它完成。

该实现的工作方式如下(详情如下):

  1. 将功能asyncForEach添加到您的代码中
  2. 上传数组时调用asyncForEach函数

实施
要实现异步上传,请执行以下操作:
.js文件的上部添加以下功能。

// implementation of asynchonous forEach   
// array: array of items to process
// callback: the asynchonous function to process the items 
async asyncForEach(array, callback) {
    for (let index = 0; index < array.length; index++) {
        await callback(array[index], index, array);
    }
}

然后调用新实现的函数,并使用以下代码行
注意:变量'imgArr'代表要上传的图像数组):

// create a function 'uploadArray' in which the asyncForEach is called. 
const uploadArray= async () => {
    await this.asyncForEach(imgArr, async (img) => {
        await this.updateImage(img);
    };
/* execute the function. The code following this function call will be 
stalled until the images are either uploaded or failed with error 
(implement error handling in the this.updateImage function
await uploadArray()

资源