JAVASCRIPT

Upload Files to API with Progress Tracking

Implement client-side file uploads to a REST API in JavaScript using `XMLHttpRequest` (XHR) or `fetch` with `FormData`, including real-time progress updates.

async function uploadFileWithProgress(url, file, onProgress, authToken) {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', url, true);

    if (authToken) {
      xhr.setRequestHeader('Authorization', `Bearer ${authToken}`);
    }

    xhr.upload.onprogress = (event) => {
      if (event.lengthComputable) {
        const percentCompleted = Math.round((event.loaded * 100) / event.total);
        onProgress(percentCompleted); // Callback for progress updates
      }
    };

    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.responseText));
        } catch (e) {
          resolve(xhr.responseText); // Handle non-JSON responses
        }
      } else {
        reject(new Error(`Upload failed with status ${xhr.status}: ${xhr.responseText}`));
      }
    };

    xhr.onerror = () => reject(new Error('Network error during file upload.'));
    xhr.onabort = () => reject(new Error('File upload aborted.'));

    const formData = new FormData();
    formData.append('file', file); // 'file' is the field name expected by the server

    xhr.send(formData);
  });
}

// Example Usage (assuming an <input type="file" id="fileInput"> and a button):
/*
document.getElementById('uploadButton').addEventListener('click', async () => {
  const fileInput = document.getElementById('fileInput');
  if (fileInput.files.length > 0) {
    const fileToUpload = fileInput.files[0];
    const uploadUrl = 'https://api.example.com/upload'; // Your API endpoint
    const token = 'YOUR_AUTH_TOKEN'; // Optional: your authentication token

    try {
      console.log(`Uploading ${fileToUpload.name}...`);
      const response = await uploadFileWithProgress(
        uploadUrl,
        fileToUpload,
        (progress) => {
          console.log(`Upload progress: ${progress}%`);
          // Update a UI progress bar here
          // document.getElementById('progressBar').style.width = `${progress}%`;
        },
        token
      );
      console.log('Upload successful:', response);
    } catch (error) {
      console.error('Upload failed:', error);
    }f
  } else {
    console.warn('No file selected.');
  }
});
*/
How it works: This JavaScript function `uploadFileWithProgress` demonstrates how to upload a file to a REST API endpoint while providing real-time progress updates. It utilizes `XMLHttpRequest` (XHR) because `fetch` API currently lacks direct support for upload progress events. The `FormData` object is used to correctly package the file for a `multipart/form-data` request, and the `xhr.upload.onprogress` event listener allows for tracking and displaying the upload percentage, enhancing user experience for larger files.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs