onUploadProgress not being called
Problem
I am setting up an axios request like so: [code block] data is a FormData object file a file resource, the data gets posted to my server correctly, but onUploadProgress never gets called, even when uploading large files (I only need to use it to upload images, just using large files for testing).
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Ensure onUploadProgress is Triggered in Axios Requests
The onUploadProgress callback may not be triggered if the request is not properly configured to track upload progress. This can happen if the FormData object is not correctly set up or if the axios instance does not have the appropriate headers or configuration for tracking progress.
Awaiting Verification
Be the first to verify this fix
- 1
Check FormData Initialization
Ensure that the FormData object is correctly initialized and that the file is appended properly. If the file is not appended correctly, the upload may not trigger progress events.
javascriptconst formData = new FormData(); formData.append('file', fileInput.files[0]); - 2
Configure Axios Request with onUploadProgress
Make sure to include the onUploadProgress option in your axios request configuration. This function will be called periodically during the upload process.
javascriptaxios.post('/upload', formData, { onUploadProgress: (progressEvent) => { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`Upload Progress: ${percentCompleted}%`); } }); - 3
Set Appropriate Content-Type Header
Ensure that the Content-Type header is set to 'multipart/form-data' when sending FormData. Axios automatically sets this when using FormData, but it's good to verify.
javascriptconst config = { headers: { 'Content-Type': 'multipart/form-data' } }; axios.post('/upload', formData, config); - 4
Test with Different File Sizes
After making the above changes, test the upload with various file sizes to ensure that the onUploadProgress callback is triggered consistently.
Validation
To confirm the fix worked, upload a file and check the console for upload progress logs. You should see progress updates as the file uploads. If the logs appear, the onUploadProgress is functioning correctly.
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep