JAVASCRIPT

Upload Files to an API with Progress Tracking using FormData

Discover how to efficiently upload files to a REST API using JavaScript's XMLHttpRequest with real-time progress tracking for a better user experience.

function uploadFileWithProgress(url, file, onProgressCallback, onErrorCallback, onSuccessCallback) {
  const xhr = new XMLHttpRequest();

  xhr.open('POST', url, true);

  xhr.upload.onprogress = (event) => {
    if (event.lengthComputable) {
      const percentCompleted = (event.loaded / event.total) * 100;
      onProgressCallback(percentCompleted);
    }
  };

  xhr.onload = () => {
    if (xhr.status >= 200 && xhr.status < 300) {
      onSuccessCallback(JSON.parse(xhr.responseText));
    } else {
      onErrorCallback(xhr.status, xhr.responseText);
    }
  };

  xhr.onerror = () => {
    onErrorCallback(xhr.status, 'Network error or server unreachable');
  };

  const formData = new FormData();
  formData.append('file', file, file.name); // 'file' is the field name expected by the API
  // You can append other fields as well:
  // formData.append('description', 'A useful document');

  xhr.send(formData);
}

// Example usage:
const fileInput = document.createElement('input');
fileInput.type = 'file';
document.body.appendChild(fileInput);

fileInput.addEventListener('change', (event) => {
  const selectedFile = event.target.files[0];
  if (selectedFile) {
    console.log('Uploading file:', selectedFile.name);
    uploadFileWithProgress(
      'https://api.example.com/upload', // Replace with your API endpoint
      selectedFile,
      (progress) => {
        console.log(`Upload progress: ${progress.toFixed(2)}%`);
        // Update UI element (e.g., progress bar)
      },
      (status, error) => {
        console.error(`Upload failed: ${status} - ${error}`);
      },
      (response) => {
        console.log('Upload successful:', response);
      }
    );
  }
});
How it works: This JavaScript snippet demonstrates how to upload a file to a REST API using `XMLHttpRequest` and `FormData`, crucially including progress tracking. `FormData` correctly formats the file for a multipart/form-data POST request. The `xhr.upload.onprogress` event listener allows you to monitor the upload's progress, providing real-time feedback to the user, while `onload` and `onerror` handle success and failure.

Need help integrating this into your project?

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

Hire DigitalCodeLabs