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

Guide on getting a website name from a URL using Javascript

Is there a simple method to extract the site name from a URL string? For example: http://www.mysite.com/mypath/mypage -> www.mysite.com http://mysite.com/mypath/mypage -> mysite.com The JavaScript code runs on the mongodb CLI side, not within ...

Encountering a 404 Error in CKFinder 3 integration with Laravel 6 and Vuejs while accessing the File Browser

My progress so far includes almost being able to successfully upload files to my Laravel installation using CKEditor and the CKFinder file browser opening from the route myurl/ckfinder/browser. However, I have encountered an issue where clicking on the ima ...

Insert fresh user information into the div

Learning JavaScript is a challenge I'm tackling. I have a question that may seem trivial, but any assistance would be greatly appreciated. I currently have this code: Javascript <script type="text/javascript"> function fn(){ var Name = ...

Exploring how to integrate a jQuery ajax request within Javascript's XmlHttpRequest technique

My current setup involves an ajax call structured like this: var data = {"name":"John Doe"} $.ajax({ dataType : "jsonp", contentType: "application/json; charset=utf-8", data : JSON.stringify(data), success : function(result) { alert(result.success); // re ...

Learning how to interpret data within configuration files (.properties) using JavaScript

I'm trying to retrieve data from a configuration file (.properties) in my code. The structure of my configuration file is as follows: maxTime = 60 upVotePostMaxTime=60 However, I am unsure of how to read this configuration file using JavaScript. Is ...

Vue component input form not providing expected result

Here is the code snippet for my "ecedata" component with an input field: <template> <div class="col-l-4"> <p style="text-align: center">Data/day (GB)</p> <div class="form-input-set" style="background: white"& ...

Getting Rid of Angular Material Suggestions: A Step-by-Step Guide

<md-autocomplete ng-model="ctrl.searchText" md-selected-item="ctrl.selectedItem" md-selected-item-change="ctrl.selectedItemChange(item)" md-search-text="ctrl.searchText" md-search-text-change="ctrl.searchTextChange(ctrl.searchText)" ...

Deploying an AngularJS 1.x application bundled with Webpack to Tomcat server

I've scoured the depths of Google and combed through the official documentation for Webpack, but I’ve yet to stumble upon a tutorial, guide, or plugin that addresses this particular issue. Does anyone have any experience with this problem, or should ...

Tips for creating a window closing event handler in Angular 2

Can someone guide me on how to create a window closing event handler in Angular 2, specifically for closing and not refreshing the page? I am unable to use window.onBeforeunLoad(); method. ...

Retrieve the username after making a call to this.$auth.fetchUser() in Nuxt

Hey there, I've been trying to retrieve the username after using the fetchUser method but it keeps showing as undefined. This is how I have been attempting: async loginUser() { this.$auth.setUserToken(`${this.token}`); this.$auth.setS ...

Nest.js: initializing properties from a superclass in a controller

I have a question about unit testing controllers in the Nest.js framework. My issue is that the property from a superclass is not initialized in the controller class when creating a test module. Here is an example of the code I am referring to: export cl ...

The FB API does not request permission to manage_pages

When logging in as the user who created the app, they are prompted to grant both manage_pages and publish_stream permissions. However, when logging in as a different user, only the publish_stream permission is requested and granted; manage_pages access is ...

What is the best way to showcase a singular item from response.data?

Below is the controller I have set up to display details of a single book from my collection of json records .controller('BookDetailsController', ['$scope','$http','$stateParams',function($scope,$http,$stateParams){ ...

Tips for preventing issues with Javascript latency causing flash out during page loading in Chrome

When building a page with Vue.js or any other Javascript, the issue of temporary flash during loading on Chrome due to constructing latency can be quite frustrating. This delay is not caused by asynchronous ajax requests, but rather the processing involv ...

Utilize a directive every instance

I need to implement an angular directive that triggers before all events like ng-click whenever the view value changes. This directive should be called as the first action when the view is changed. Check out the JSFiddle example. angular.module('myA ...

The requested 'Pagination' component (imported as 'Pagination') could not be located within the 'swiper' library. Possible exports include Swiper and default

I was trying to implement pagination using swiper. I included the Pagination module with this import statement: import { Pagination } from "swiper"; Here's my configuration: The error that I encountered is : I have noticed that it w ...

The JavaScript library known as Microsoft JScript Angular is not recognized

While integrating Angular into my .Net MVC website, I keep running into a runtime error that reads as follows: 0x800a1391 - Microsoft JScript Runtime Error: 'angular' is undefined. This essentially means that the 'angular' object ...

JS Month Interval Bug Causing Issues with Chart Date

This script retrieves and summarizes download data from MySQL by day, displaying it as a chart. However, there's an issue with the way dates are handled between PHP and JavaScript (Highcharts). While PHP outputs month values from 1 to 12, JavaScript c ...

Using Node.js and the Azure DevOps Node API, you can easily retrieve attachments from Azure DevOps work items

Encountering a problem while attempting to download an attachment for a work item in Azure DevOps. Utilizing the node.js 'azure-devops-node-api' client (https://www.npmjs.com/package/azure-devops-node-api) to communicate with ADO API. Retrieving ...

Encountering a "require is not defined" error when trying to launch a Selenium

I have developed a basic selenium application and now I am looking to implement a graphical user interface for it. Here is the code snippet: index.html: <html> <head> <meta charset="UTF-8" /> <title>Selenium Ap ...