onuploadprogress axios typescript example
- User
onuploadprogress axios typescript example
- Assistant
To handle upload progress with Axios in a TypeScript environment, you can use the
onUploadProgressproperty of the Axios request configuration. This property allows you to set a function that will be called during the upload of a request, providing information about the progress of the upload.Here's an example demonstrating how to use
onUploadProgresswith Axios in TypeScript:import axios, { AxiosRequestConfig } from 'axios'; // Define the interface for the progress event interface UploadProgressEvent extends ProgressEvent { loaded: number; // The number of bytes uploaded so far total: number; // The total number of bytes to be uploaded } async function uploadFile(file: File) { const formData = new FormData(); formData.append('file', file); // Create the Axios request configuration const config: AxiosRequestConfig = { method: 'post', url: 'YOUR_UPLOAD_ENDPOINT', data: formData, headers: { 'Content-Type': 'multipart/form-data', }, onUploadProgress: (progressEvent: UploadProgressEvent) => { const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`Upload Progress: ${percentCompleted}%`); }, }; try { const response = await axios(config); console.log('File uploaded successfully', response); } catch (error) { console.error('File upload failed', error); } } // Example usage: // Assuming you have a file input in your HTML: // <input type="file" id="fileInput" name="file"> const fileInput = document.getElementById('fileInput') as HTMLInputElement; fileInput.addEventListener('change', function() { if (this.files && this.files[0]) { uploadFile(this.files[0]); } });In the example above,
axiosis used to send a POST request to upload a file. TheonUploadProgresscallback function calculates the percentage of the upload that has completed and logs this information to the console. This function is triggered periodically during the upload, providing real-time feedback on the progress.You need to replace
'YOUR_UPLOAD_ENDPOINT'with the actual URL where you want to upload the file. This could be an API endpoint on your server configured to handle file uploads.Also, ensure you have the proper backend setup to handle the multipart/form-data request generated by this code, as well as proper error handling on both the client and server sides for a robust application.