Progress of file uploads on the client side using Vue JS

I'm facing a challenge in creating a loading bar that shows the progress when a file is selected for upload in a form. Most of the examples I come across online demonstrate the loading bar after hitting an 'upload' button, but in my case, I want to display the loading progress immediately after selecting the file, even before hitting the submit button. So, once a file is added to the input field, a loading percentage should be visible. I would greatly appreciate any guidance on how to achieve this.

FileUpload.vue - file upload input component

 <div class="container">
    <!--UPLOAD-->
      <h3 class="form-input-title">{{labelText}}</h3>
      <div class="dropbox">
        <img src="../../assets/img/icon/curr/ic_download.svg"
             class="download-icon"
             alt="download icon"/>
        <input :name="fieldName"  
               :accept="accept"
               @change="loadFile($event)"
               type="file"
               class="input-file">
          <p v-if="!isLoading && !isSuccess">{{text}}</p>
          <p v-if="isLoading">Uploading files... {{uploadLoadPercentage}}</p>
          <p v-if="isSuccess">{{fileName}}</p>
      </div>
  </div>


<script>
  import {ref, watch} from '@vue/composition-api';
  import Validator from "@/utils/yo-validator/YoValidator";

  export default {
    name: 'FileUpload',

    setup(props) {
      /** validator returned error messages **/
      const {errorMessages, validateFieldByData, setFieldData} = Validator.register(props);

      /** watch api error text from parent **/
      const apiError = ref('');
      watch(() => props.apiErrorText, (newVal) => {
        apiError.value = newVal.trim();
      });

      const isLoading = ref(false);
      const isSuccess = ref(false);
      const uploadFailed = ref(false);
      let uploadLoadPercentage = ref(0);
      const fileName = ref('');
      /** watch input in the template **/
      const loadFile = async (event) => {
        // TODO: File loading > When the file is selected, check how long the file (in bytes) takes to upload
        // If the loading is successful proceed without any errors

        // validate the image
        validateFieldByData(event.target.files);

        // define data
        const data = props.isMultiple ? event.target.files : event.target.files[0];

        // set the name of the file that has been uploaded.
        fileName.value = event.target.files[0].name;

        // Once loading and validation is completed, save the data
        saveFile(data);
      };

      const saveFile = (data) => {
        // Once saveFile is triggered, the upload value will be successful.
        isSuccess.value = true;

        // update form data
        setFieldData(data);
        // call the parent if needed
        updateParent(data);
      }
  
      // update parent component
      const updateParent = (data) => {
        if (props.callback) {
          props.callback(data);
        }
      };
      const clearFile = (event) => {
        // clear the value to trigger change event for uploading the same image
        event.target.value = null;
      };

      return {
        errorMessages,
        apiError,
        loadFile,
        clearFile,
        isLoading,
        isSuccess,
        uploadFailed,
        fileName,
        uploadLoadPercentage
      }
    }
  }
</script>

Answer №1

Tracking progress for a file upload is essential when sending it to a server or storage space. Typically, a POST or PUT request is made using a library like axios, which includes an onUploadProgress callback to monitor progress. For more detailed examples, refer to resources like the answer on Stack Overflow here.

If you encounter a special case, such as uploading through Firebase, specific tools are available. Providing more information about your scenario can help provide a more tailored solution.

UPDATE: Apologies for the misunderstanding earlier. Here's a code snippet that demonstrates handling file uploads in Vue.js. This code uses a FileReader object to track progress and display the uploaded file.

Simply create a Reader object to manage the upload process and listen for events emitted by it. Feel free to ask if you have any further questions. The console output can also be utilized to display data on the UI.

For images, a progress indicator may not be necessary due to their fast upload times. However, for larger files, including the HTTP request for upload can be beneficial. Adjust the approach based on the type of files being uploaded.

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

In JavaScript, capture data returned from a function in a separate variable using a POST REST API call

So, here's the deal - I've got this awesome code that does a POST to an API in order to fetch some data. The best part? It works like a charm when it's wrapped up neatly in a function. But now, the tricky part comes in. I need to actually re ...

Is there a way for me to write on a website and have my content instantly show up on a different hosting

Similar Question: Web based text chat? I am looking to develop a website that enables me to type in a textbox and have the content displayed on another user's screen. Can anyone assist me with this task? Thank you! Amen ...

Show only the populated fields in a user profile with ReactJS

Purpose Showcasing only completed fields. Context In my app, users fill out an application with fields like "early reg fee, early reg date, regular reg fee, regular reg date". After completing all the information and clicking "view profile", they should ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: https://i.sstatic.net/IxcnK.png HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-oute ...

Creating an element that remains fixed once it reaches a distance of 50px from the top of the screen

Hey there! I'm working with an html div element that currently scrolls along with the page, but I was wondering how I can make it become fixed once it reaches a distance of 50px from the top of the screen. Any ideas on how to achieve this? Just to pro ...

Vuejs has the capability for dynamic image binding which allows for images to be dynamically loaded and displayed based on

I'm having trouble figuring out how to dynamically bind an image in Vuejs from an external site. Here's the code that is currently working: <v-btn v-for="item in items" :key="item.id" :to="item.path" color="white" class=" ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

How to implement form modal binding using Laravel and Vue.js

There are two models named Tour.php public function Itinerary() { return $this->hasMany('App\Itinerary', 'tour_id'); } and Itinerary.php public function tour() { return $this->belongsTo('App\Tour', ...

How to transform a file into a uInt8Array using Angular

Looking to implement a feature where I can easily upload files from Angular to PostgreSQL using a Golang API. In my Angular component, I need to convert my file into a uInt8Array. I have managed to convert the array, but it seems to be encapsulated in som ...

Store the result of the previous AJAX call in a jQuery variable and combine it with the data from the next AJAX response

I am working on a program where I retrieve price values using ajax. My goal is to add the previous price value to the current price value when it is retrieved again. The issue I am facing is that each time I get a new price value, it overrides the previou ...

Guide on running a MySQL query in an asynchronous function in a Node.js application

Encountering some challenges while using MySQL in a node/express JS application. It seems that when trying to access the MySQL database within an asynchronous function, the code will 'skip over' the SQL query and run synchronously. This is the co ...

A guide on extracting content from a PDF file with JavaScript

Hey there, I'm experimenting with various methods to extract content from a PDF file but so far nothing seems to be working for me. Even when I try using pdf.js, it shows an error and I can't figure out why. This is the approach I've been tr ...

Encountering a 401 error while attempting to exchange Faceit OAuth authorization code for access token

I am having issues with exchanging a code for a token on the Faceit OAuth. The documentation states the following: Exchanging the Authorization Code for an Access Token The third-party app needs to make a server-to-server call, providing the Authorization ...

Do you have any queries regarding JavaScript logical operators?

I'm struggling with understanding how the && and || operators work in my code. I created a small program to help myself, but it's just not clicking for me. The idea is that when you click a button, the startGame() function would be triggered. va ...

Tips for resolving asynchronous s3 resolver uploads using Node.js and GraphQL

My goal is to upload an image and then save the link to a user in the database. Below is my GraphQL resolver implementation: resolve: async (_root, args, { user, prisma }) => { .... const params = { Bucket: s3BucketName, ...

How to prevent collapse when selecting a node in React.js Mui Treeview

Is there a way to prevent the Treeview from collapsing every time a node is selected? I want it to render a button based on the selected node. Here's an example that I've created: https://codesandbox.io/s/summer-water-33fe7?file=/src/App.js ...

When trying to manually trigger the firing of the autocomplete function to get a place using Google API

My goal is to retrieve the data from autocomplete.getPlace() when triggering this event manually. Essentially, I have a function that captures the user's location in Lat/Lng format, and afterward, I aim to access other useful data using getPlace() su ...

Merge the elements of one array with the elements of another array simultaneously

Can a function be created that combines each value from two arrays, even if the arrays are of different lengths? For example: arr1 = ["apple", "banana", "cherry"]; arr2 = ["pear", "kiwi", "orange"] mergedArr= ["applepear", "applekiwi", "appleorange", " ...

Developing Angular 2 custom async validators for use in reactive forms

I am currently working on a reactive form that requires unique form controls: this.form = new FormGroup({ name: new FormControl(this.initialValue, [ Validators.required, ], this._uniqueNameValidator.bind(this)), }); To achieve this, I have create ...

What is the best way to apply styling to an image that is contained within the document.write function?

I'm looking to customize the design of this cat image, but I'm struggling to locate where to incorporate the div class. It's likely a basic step, but as a beginner in JavaScript, I'm hoping that someone can assist me. document.write(&ap ...