乐闻世界logo
搜索文章和话题

How to get onUploadProgress in axios?

1个答案

1

When using axios for file uploads, tracking upload progress can be achieved by configuring the onUploadProgress property during request setup. onUploadProgress is a function invoked during the upload process that accepts a ProgressEvent as a parameter, enabling us to retrieve relevant progress information. Here is an example of using axios to track upload progress:

javascript
const axios = require('axios'); // The file data to be uploaded const file = /* obtain file data, for example, document.getElementById('file').files[0] */; // Create a FormData object and append the file const formData = new FormData(); formData.append('file', file); // Initiate a POST request to upload the file axios({ method: 'post', url: '/upload', // Your upload URL data: formData, headers: { 'Content-Type': 'multipart/form-data' }, onUploadProgress: function(progressEvent) { // Calculate upload progress const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); // Log or handle upload progress console.log(`Upload progress: ${percentCompleted}%`); // For example, you can update the status of a progress bar here } }) .then(response => { // Handle response data console.log('File upload successful', response); }) .catch(error => { // Handle error cases console.error('File upload failed', error); });

In this example, I first require the axios module, then prepare the file data to be uploaded and add it to a FormData object. When configuring the axios request, I specify the method as post, the url as the upload endpoint, and pass the formData as the data.

Within the request configuration object, I define the onUploadProgress function. This function receives a ProgressEvent object, which we can use to calculate the current upload progress percentage by accessing the loaded and total properties. This progress information can be used to update the UI, such as a progress bar, or simply printed to the console.

Finally, the successful response is handled via then, and potential errors are caught and processed via catch. Since this process is asynchronous, UI updates should occur within the onUploadProgress function to ensure users can see real-time upload progress.

2024年6月29日 12:07 回复

你的答案