How to Track Upload Progress in Axios

Tracking upload progress in Axios allows developers to monitor real-time data transfer and display upload status indicators, such as progress bars, to users. This article explains how to use the built-in onUploadProgress callback function provided by Axios, how to calculate upload percentages accurately, and how to implement this functionality in standard JavaScript and frontend frameworks.

The onUploadProgress Configuration

Axios provides a dedicated configuration property named onUploadProgress. This is a callback function that executes multiple times during the upload lifecycle as chunks of data are sent to the server. The callback receives a progressEvent object containing metadata about the current transfer.

Step-by-Step Implementation

  1. Prepare the Data: Create a FormData object and append the file(s) you wish to upload.
  2. Configure the Request: Pass an options object as a parameter to your axios.post or axios.put call containing the onUploadProgress callback.
  3. Calculate the Percentage: Access progressEvent.loaded (bytes transferred so far) and progressEvent.total (total file size in bytes). Divide loaded by total and multiply by 100 to get the completion percentage.

Code Example

import axios from 'axios';

async function uploadFile(file) {
  const formData = new FormData();
  formData.append('file', file);

  try {
    const response = await axios.post('/api/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
      onUploadProgress: (progressEvent) => {
        if (progressEvent.total) {
          const percentCompleted = Math.round(
            (progressEvent.loaded * 100) / progressEvent.total
          );
          console.log(`Upload Progress: ${percentCompleted}%`);
          // Update your UI state/progress bar here with percentCompleted
        } else {
          console.log(`Uploaded ${progressEvent.loaded} bytes (total size unknown)`);
        }
      },
    });

    console.log('Upload complete:', response.data);
  } catch (error) {
    console.error('Upload failed:', error);
  }
}

Key Considerations