MajesticOverlord
MajesticOverlord

Reputation: 101

How to upload multiple files to firebase storage in the order they were selected?

I have been using Firebase storage to save multiple images and then store their URL in the firestore to display the images in the front end. The URL's are being stored in an array field in the firestore. However when I upload multiple images to the storage they don't upload in the order they were selected (the order is the images by their name). They all upload simultaneously hence the shorter sized images get uploaded first and the images don't get displayed in the order they were selected. How do I upload the next image only after the previous image is uploaded?

I am using the Vue for my project

I have converted the Files List node into an array and used a forEach loop to go through each individual file and store it in the firebase storage.

<input v-on:change.prevent='imageList' type="file" multiple name ='pImages' 
id = 'pImages'>
const pfInput = document.querySelector('#pImages').files;
const pI = Array.prototype.slice.call(pfInput);

pI.forEach((image) => {
// Storing Images in firebase cloud storage
const uploadTask = storage.ref(`projects/${this.pUsername}/${image.name}`)
                           .put(image)

uploadTask.on('state_changed', (snapshot){} , (error){} , 
()=>{
   storage.ref(`projects/${this.pUsername}`).child(image.name)
                                            .getDownloadURL()
                                            .then((url) => {
  //Code to store the URL to firestore
)
})

The front end displays images in the index order of the array that storees the URL's. Since the files simultaneously upload the shorter ones get uploaded first and hence their URL's get stored first. So the files don't display in the order they were selected on the PC (By name).

I want to upload the files in the order they were selected.

Could you please help me fix this issue?

Upvotes: 1

Views: 1722

Answers (1)

MajesticOverlord
MajesticOverlord

Reputation: 101

I figured out a solution to this. I stored all the URL's in the random order in an array and used a .then() where i sorted my list. I realized that the URL's of the image are in order by their name so when you use array sort the URL's rearrange themselves in the order of the files.

After the

.then((url)=>{
//Get URL of images
this.imageList.push(url)
}) 

you can:

.then(()=>{
 this.imageList.sort() //Sorts the list URL's in the order of the file name.
}

Upvotes: 0

Related Questions