Issue with file reader not loading initially in VUE.JS

I've encountered an issue with a file reader where it only loads the file properly from the second time onwards, behaving like a queue. The first time I select a file, it seems to skip loading.

Is there a way to resolve this problem?

Below is the code snippet:


  <v-text-field
    v-if="switch1"
    label="Upload Fattura"
    @click='onPickFile'
    v-model='fatturaFileName'
    prepend-icon="mdi-paperclip"
  ></v-text-field>
  <input
    type="file"
    style="display: none"
    ref="fileInput"
    accept="text/xml"
    @change="onFilePicked"
  >

  onPickFile () {
    this.$refs.fileInput.click();
  }

  onFilePicked (event) {
    if (event) event.preventDefault();
    var files = event.target.files[0];
    if (files !== undefined) {
      this.fatturaFileName = files.name;

      // If valid, continue
      const fr = new FileReader();
      fr.readAsText(files);
      fr.addEventListener('load', () => {
        this.fatturaUpload = fr.result;
      });
    } else {
       this.fatturaFileName = ''
       this.fatturaFileObject = null
    }
    console.log(this.fatturaUpload);
  }

Answer №1

Here is the code snippet that successfully handles file uploading:

onFilePicked (event) {
      if (event) event.preventDefault();
      var fichier = event.target.files[0];
      if (fichier != undefined) {
           const fr = new FileReader();
        fr.readAsDataURL(fichier);
        var reader = new FileReader();
        let file = fichier;
        reader.readAsText(file, "UTF-8");
        reader.onload = evt => {
            console.log("1",evt.target.result)
        };
      } else {
        console.log("2",fichier)
         this.fatturaFileName = ''
         this.fatturaFileObject = null
      }
      console.log("3",this.fatturaUpload);
       this.fatturaFileName = '';
       this.fatturaFileObject = null;

    }


Check out the live demo on CodePen to see it in action.

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

The Reactjs dependency tree could not be resolved

In my current project, I've been attempting to integrate react-tinder-card. After running the command: npm install --save react-tinder-card I encountered this error in my console: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency ...

Ways to prevent the "Site not secure" warning on an Express server with HTTPS configuration

In the process of creating an Express app, I decided to enable HTTPS for a secure connection. After obtaining a certificate from StartSSL.com and importing it into my server successfully, everything seemed set up correctly. However, an issue has arisen: h ...

Is there a way to identify a change in the URL using JQuery?

My goal is to clear the localStorage when a user navigates to a different page. For instance, if I am currently on . When the user goes to the URL, , I want to clear the localStorage. This is my script using JQuery. $(window).unload(function(){ if ...

How can SQL data be loaded following the selection from a dropdown menu?

I have a pressing query that I need assistance with. I am aiming to achieve a certain task, but due to lack of prior experience in this area, I am unsure about how to proceed. My current situation involves populating a dropdown menu with names retrieved f ...

Nuxt3 Generate - Ensuring asynchronous data is ready before pre-rendering

<template> <article class="post" v-if="post"> <section v-html="post.content" ></section> </article> </template> <script setup lang="ts"> c ...

Ways to filter and display multiple table data retrieved from an API based on checkbox selection in Angular 2 or JavaScript

Here is a demonstration of Redbus, where bus data appears after clicking various checkboxes. I am looking to implement a similar filter in Angular 2. In my scenario, the data is fetched from an API and stored in multiple table formats. I require the abili ...

What is the best way to integrate Vuex State data into methods?

Reviewing the code snippet below: <template> <div :id="svgId" class="svg-container"></div> </template> <script> import { mapState } from 'vuex' export default { name: 'Space', data: function() { ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Angular and dropdowns: a perfect match

Imagine having a controller like this: myApp.controller('testCtrl', function ($scope) { $scope.cars = [ { carId: '1', carModel: 'BMW', carOwner: 'Nader' }, { carId: '2', carModel: &apos ...

Display loading spinner as component loads

I've been developing a Vue application where a single Vue instance expands into multiple other components. //import <Loader/> const componentOne = Vue.extend({ mounted: function() { this.$root.$data.componentOneLoading = false } //... ...

What is the best way to store objects containing extensive binary data along with additional values?

I'm currently working on saving a JavaScript object that includes binary data along with other values. I want the output to resemble the following: { "value":"xyz", "file1":"[FileContent]", "file2&quo ...

When using jQuery to add an item to a List, it disappears immediately after

I am facing an issue with the code I have. Whenever I click on the "Add" button to add an item, it briefly appears in the list but then disappears. I'm having trouble figuring out why this is happening. $(document).ready(function() { $("#submitB ...

Troubleshooting issue with jQuery/Javascript custom email validation not functioning as expected

I attempted to create my own email validation without using a plugin, but it's not functioning correctly. The code I wrote always returns false. Here is the snippet: var regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i; ...

"Enhance your Vue application with the powerful combination of Vue

I'm facing an issue with getting vue-resource to work alongside vueify. I have created a Vue component that I am including in my main.js file. import Vue from 'vue' import MyComponent from './my-component.vue' new Vue({ el: & ...

The default value for the ReturnType<typeof setInterval> in both the browser and node environments

I have a question about setting the initial value for the intervalTimer in an Interval that I need to save. The type is ReturnType<typeof setInterval>. interface Data { intervalTimer: ReturnType<typeof setInterval> } var data : Data = { ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

Unable to utilize the 'require' function in subdirectories within the node_modules directory

In the development of my express api, I have set up routes as a dependency within the main project. The main project contains a config folder with an index.js file that exports an object serving as the route configuration. While I can access this exported ...

Trouble with recognizing nested functions when calling them in an onClick event

Encountering a `not defined` error on the console when attempting to call nested functions with an `onClick` event in an HTML page. After searching for solutions without success, I suspect it may be a scope or closure issue, but I am unsure of how to addre ...

Eliminate an array from another array if a specific value is present in an object

I've been struggling with removing an entire array if it contains an object with a certain value within. I've searched high and low, but haven't been able to find a solution that fits my specific problem. In my data structure, I have arrays ...

What is the best way to change the "MuiPaper-elevation1" attribute in a Card element within Material-UI?

My Card component in HTML looks like this: <div class="MuiPaper-root MuiCard-root makeStyles-Card-5 MuiPaper-elevation1 MuiPaper-rounded"> I want to change MuiPaper-elevation1 to MuiPaper-elevation0 to remove the shadow. I attempted: ...