Learn the steps to upload multiple images to Firebase realtime database with the help of Vuejs

I am currently facing an issue with uploading multiple images to a real-time Firebase database. I have successfully managed to upload one image, but I am unsure how to handle multiple images at once.

This is the code snippet for uploading a single image:

<v-layout row>
          <v-flex xs12 sm6 offset-sm3>
            <!-- Using 'accept' attribute to only allow image files -->
            <v-btn raised @click="onPickFile">Upload image</v-btn>
            <input
              type="file"
              style="display:none"
              ref="fileInput"
              accept="image/*"
              @change="onFilePicked"/></v-flex
        ></v-layout>

In my data object, I have two properties: imgURL: "", image: null. The following method handles the file selection:

onFilePicked(event) {
  const files = event.target.files;
  let filename = files[0].name;
  if (filename.lastIndexOf(".") <= 0) {
    return alert("Please add a valid file!");
  }
  const fileReader = new FileReader();
  fileReader.addEventListener("load", () => {
    this.imgURL = fileReader.result;
  });
  fileReader.readAsDataURL(files[0]);
  this.image = files[0];
},

Answer №1

While this question may not be directly related to Firebase, I'll do my best to offer some assistance:

To enable selection of multiple files in an input tag, you should add the multiple attribute:

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

If you encountered an issue with a 'for-loop' for files, try using of instead of in to access the file itself instead of just the index:

I've separated key parts of your function and converted them into asyncronous Promises to prevent timing errors with addEventListener:

This is a basic implementation for uploading multiple files. It might be beneficial to include additional error handling:

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() {
      //... Perform firebase upload operations here:
      console.log(this.blobs)
      //...
    }
  }
})

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using *ngIf to construct SVG icons in Angular 2 doesn't contribute to the DOM in any way

I am currently utilizing icoMoon to import a series of SVG icons. The structure of the html I'm trying to create using ngIf is as follows: <div class="contactIcon"> <svg class="icon icon-envelop"> <use xlink:href="symbol-d ...

Send PHP data through AJAX and retrieve it on a different PHP page

I need to send a variable through an AJAX URL to another PHP page and retrieve it using: $id=$_GET['id']; Here's an example where the value is passed, for instance $id=6. <a id="pageid" href="ifsc-bank.php?id=<?=$id?>"><im ...

Utilize dynamically generated form fields to upload multiple files at once

Currently, as I delve into learning the MEAN stack, I am encountering difficulties with file uploads. Specifically, within a company form: this.companyForm = this.fb.group({ trucks: this.fb.array([]), ... }); The 'trucks' field i ...

Error message: "Using AngularFire 2 caused an issue as Firebase is not identified as a

I am interested in creating a sample app using Ionic 2 and AngularFire 2. After successfully integrating AngularFire 2 into Ionic 2, I encountered an error while trying to retrieve data from Firebase. The error message displayed in the browser console: ` ...

Iterate through each row asynchronously, waiting for each one to complete before moving on to the

Trying to navigate through multiple pages using puppeteer has been successful, except when attempting to parse through them at the same time. The issue seems to stem from the code executing async operations in rapid succession, overwhelming the browser. My ...

Exploring the Form's data-url Attribute

My form tag is set up like this: <form data-id="213" method="post" onsubmit="javascript: startAjax(); return false;"> <input type="submit" value="submit"> </form> When I submit the form, an ajax script runs to validate some information ...

Using the OR Operator with a different function in React

Struggling with setting the day flexibility using disableDate(1,2,3,4,0) but it's not functioning as expected. Can you assist me in fixing this issue? Here is the function snippet: const disableDate = (date) => { const day = date.day(); retur ...

Update the array with the new data by setting the state

Is it possible to edit and save data in an array while iterating through it using this.state.data.map()? If so, what is the best approach to achieve this? Check out this live example for reference. Below is a sample code snippet: class App extends React ...

What could be causing the slow build time for npm run serve on a Vue.js project?

My Vue.js project was running smoothly until about an hour ago when I noticed that it is now taking a very long time to build. Specifically, it gets stuck at 32% for more than 5 minutes. Does anyone have any suggestions on how to fix this issue? I'm n ...

Ways to activate a function upon validation of an email input type

Within my HTML form, there is an input type="email" field that requires a valid email pattern for acceptance. I am attempting to send an AJAX request to the server to confirm whether the entered email already exists in the database after it has been verif ...

Looking to $post the text strings within select boxes, rather than just their values

Looking to extract the text of select boxes, rather than just their values. HTML : <select name="one" id="one"> <option value="0">Select *</option> <option value="3000">Plan A</option> <option value="6000"> ...

Inquiring about the Model component within the MVC architecture in a web application created with NodeJs and integrated with

As a beginner in NodeJs, I am venturing into creating web applications using the express framework and MySQL. Understanding that in MVC architecture, views are represented by *.ejs files, controllers handle logic, and models interact with the database. Ho ...

JavaScript sorting through nested functions

Having an issue with running a function inside another function for my Bingo game script. The checkBingo() function is defined outside of a .click() function, but I'm facing problems. Ajax is involved, so that might be contributing to the issue. Here& ...

using javascript to change a link's state with a click action

I have a question that is related to the topic discussed here: Making a link stay active displaying hover effect upon click using javascript. I am looking for a way to disable the active class when the same link is clicked again. Any assistance on this mat ...

How to eliminate duplicate items in an array using various criteria

I have an array arr that needs to be cleaned up by removing duplicate objects with the same e_display_id and e_type as P. In this scenario, only objects with status==='N' should be considered. Here is the input array arr: let arr = [ { e_type ...

Guide on how to create a custom response using class-validator in NestJS

Is it feasible to customize the error response generated by class-validator in NestJs? The default error message structure in NestJS looks like this: { "statusCode": 400, "error": "Bad Request", "message": [ { "target": {} ...

React Material UI unselect

I have been exploring a MUI select field implementation using this example as a guide. While I was able to make the code work, there are a few issues that I encountered. One of them is the inability to deselect a value once it has been selected. Additional ...

Application route is failing to direct to the HTML page

On my MEAN stack website, I am trying to make the browser navigate to a file named 'findCable.html' but it keeps directing to 'singleCable.html'. I have double-checked the angular routing file and backend routes, but can't see ...

Obtaining localStream for muting microphone during SIP.js call reception

My approach to muting the microphone involves using a mediastream obtained through the sessionDescriptionHandler's userMedia event. session.sessionDescriptionHandler.on('userMedia', onUserMediaObtained.bind(this)) function onUserMediaObta ...

Link the selector and assign it with its specific value

Greetings, I am a newcomer to React Native and I am currently using Native Base to develop a mobile application. I am in the process of creating a reservation page where I need to implement two Picker components displaying the current day and the next one ...