Calculating the upload progress using Readable Streams in the Fetch API can be a bit tricky, and it might not work as expected in some cases. The Fetch API does not directly provide progress events for uploading data, so you'll need to use the ReadableStream API to manually calculate the progress.

Here's a step-by-step guide to implement file upload with progress calculation using Fetch and Readable Streams:

Step 1: Create a function to upload the file using Fetch and a ReadableStream:

javascript
async function uploadFileWithProgress(url, file) { const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': file.type, }, body: file, }); return response; }

Step 2: Use the uploadFileWithProgress function to upload the file and track the progress:

javascript
async function handleFileUpload(file) { try { const uploadUrl = 'your_upload_endpoint_here'; const response = await uploadFileWithProgress(uploadUrl, file); if (response.ok) { console.log('Upload completed successfully!'); } else { console.error('Upload failed with status:', response.status); } } catch (error) { console.error('Error during upload:', error); } } // Assuming you have a file input in your HTML const fileInput = document.getElementById('fileInput'); fileInput.addEventListener('change', (event) => { const file = event.target.files[0]; handleFileUpload(file); });

Step 3: On the server-side, ensure that you send back appropriate responses, such as status codes and success messages, to indicate the upload status.

Keep in mind that the ReadableStream API is not fully supported in all browsers. It is well-supported in modern browsers, but older versions might have limited or no support. Make sure to check the browser compatibility before relying on ReadableStream for progress tracking.

Additionally, if you need more fine-grained control over the progress reporting, consider using libraries like axios, which provide built-in progress event listeners for file uploads. Axios wraps the XMLHttpRequest API, which natively supports progress events for uploads.

For example, using Axios:

javascript
import axios from 'axios'; const uploadUrl = 'your_upload_endpoint_here'; const config = { onUploadProgress: (progressEvent) => { const progress = Math.round((progressEvent.loaded * 100) / progressEvent.total); console.log(`Upload progress: ${progress}%`); }, }; axios.post(uploadUrl, file, config) .then((response) => { console.log('Upload completed successfully!'); }) .catch((error) => { console.error('Error during upload:', error); });

By using Axios, you get more control over the progress reporting, and you don't have to deal with Readable Streams directly.

Have questions or queries?
Get in Touch