简体   繁体   中英

Trying to upload multiple images to firestore with Nodejs (ClientSide firebase SDK)

I am trying to upload multiple images to firestore in my nodeJS server-side code. I initially implemented it with the firestore bucket API

admin.storage.bucket().upload()

I am placing the above code in a for loop.

for(let x = 0; images.length > x; x++){
  admin.storage.bucket().upload(filepath, {options}).then(val => {
    //get image download URL and add to a list
    imageUrls.push(url);

    if(images.length == x+1){
      // break out of loop and add the imagesUrls list to firestore
    }
  })
}

but what happens is that the code sometimes doesn't add all the image urls to the imageUrls list and I'll have only 1 or 2 image urls saved to firestore while in firestorage I see it uploaded all the images.

I understand that uploading takes some time and would like to know the best way to implement this as I assumed the .then() method is an async approach and would take care of any await instances.

Your response would be highly appreciated.

It's not clear how you get the values of filepath in the for block, but let's imagine that images is an array of fully qualified paths to the images you wish to upload to the bucket.

The following should do the trick (untested):

const signedURLs = [];

const promises1 = [];
images.forEach(path => {
    promises.push(admin.storage.bucket().upload(filepath, {options}))
})

Promise.all(promises1)
.then(uploadResponsesArray => {
    const promises2 = [];
    const config = {  // See https://googleapis.dev/nodejs/storage/latest/File.html#getSignedUrl
        action: 'read',
        expires: '03-17-2025',
        //...
        };
    uploadResponsesArray.forEach(uploadResponse => {
        const file = uploadResponse[0];
        promises2.push(file.getSignedUrl(config))
    })
    return Promise.all(promises2);
})
.then(getSignedUrlResponsesArray => {
    signedURLs.push(getSignedUrlResponsesArray[0])
});

// Do whatever you want with the signedURLs array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM