[Vuejs]-How to add multiple images to Firebase realtime database using Vuejs?

0👍

Although, this is not a firebase related question, but I try to help anyway:

First of all, you should add multiple to the input-tag, so you can select more than only one file there:

// CHANGE THIS:
<input type="file" style="display:none" ref="fileInput" accept="image/*" @change="onFilePicked"/>
// TO THIS:
<input type="file" style="display:none" ref="fileInput" accept="image/*" @change="onFilePicked" multiple/>

I assume you stumbled upon this wierd ‘for-loop’ for the files.. I had the same issue and figured out when I type of instead of in, then I get the file itself, not just the index and there is no error.

I splitted up the main parts of your function and converted them in asyncron Promises (because there might be a timing error with the addEventListener)

This is just the idea of the multiple files upload. Maybe you should add some more error-catcher:

new Vue({
  data: {
    blobs: [],
    images: [],
  },
  methods: {
    async onFilePicked(event) {
      const files = event.target.files
      this.images =[]
      this.blobs =[]
      for (let file of files) {
        this.images.push(file)
        let blob = await this.prepareImagesForUpload(file)
        this.blobs.push(blob)
      }
      this.uploadImagesToFirebase()
    },
    prepareImagesForUpload(file) {
      return new Promise((resolve, reject) => {
        let filename = file.name
        if (filename.lastIndexOf(".") <= 0) {
          alert("Please add a valid file: ", filename)
          reject()
        }
        const fileReader = new FileReader()
        fileReader.readAsDataURL(file)
        fileReader.addEventListener("load", async () => {resolve(fileReader.result)})
      })
    },
    uploadImagesToFirebase() {
      //... do the firebase upload magic with:
      console.log(this.blobs)
      //...
    }
  }
})

Leave a comment