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
- Prepare the Data: Create a
FormDataobject and append the file(s) you wish to upload. - Configure the Request: Pass an options object as a
parameter to your
axios.postoraxios.putcall containing theonUploadProgresscallback. - Calculate the Percentage: Access
progressEvent.loaded(bytes transferred so far) andprogressEvent.total(total file size in bytes). Divideloadedbytotaland 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
- Check for
totalValue: In some network configurations,progressEvent.totalmay be undefined if theContent-Lengthheader cannot be determined. Always verify thatprogressEvent.totalexists before computing a percentage. - Axios v1.x Updates: In Axios versions 1.x and
newer,
progressEvent.progressis also provided as a decimal value between0and1, which can be multiplied by 100 as an alternative calculation method (progressEvent.progress * 100). - UI Performance: Because the progress event fires frequently, avoid running expensive operations inside the callback. Update only the specific reactive state or DOM element dedicated to the progress display.