JAVASCRIPT

Download Files from API with Progress Tracking

Learn to download files from an API endpoint using Fetch API with real-time progress updates, enhancing user experience for large file transfers.

async function downloadFileWithProgress(url, filename, onProgress) {
  try {
    const response = await fetch(url);
    
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    const contentLength = response.headers.get('Content-Length');
    let receivedLength = 0;
    const reader = response.body.getReader();
    const chunks = [];

    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        break;
      }

      chunks.push(value);
      receivedLength += value.length;

      if (contentLength && onProgress) {
        const progress = Math.round((receivedLength / contentLength) * 100);
        onProgress(progress, receivedLength, contentLength); // Callback for progress updates
      }
    }

    const blob = new Blob(chunks);
    const downloadUrl = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = downloadUrl;
    a.download = filename; // Set the download file name
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(downloadUrl); // Clean up the URL object

    console.log(`File '${filename}' downloaded successfully.`);
    return blob;
  } catch (error) {
    console.error('Error downloading file:', error);
    throw error;
  }
}

// Example usage:
// Assuming an API endpoint that serves a file, e.g., 'https://example.com/api/download/report.pdf'
// const fileUrl = 'https://jsonplaceholder.typicode.com/photos/1'; // Example using a JSON endpoint, but would work for binary
// downloadFileWithProgress(fileUrl, 'my_report.pdf', (progress, received, total) => {
//   console.log(`Downloaded: ${progress}% (${received} of ${total} bytes)`);
//   // Update a UI progress bar here
// })
// .then(() => console.log('Download complete'))
// .catch(error => console.error('Download failed:', error));
How it works: This snippet provides a client-side JavaScript function to download files from an API endpoint, crucially including real-time progress tracking. It uses the Fetch API's `Response.body.getReader()` to stream the response, allowing for incremental updates on the download status. This is highly useful for large files, as it provides a better user experience by informing the user about the download progress instead of waiting silently until the entire file is transferred. Once complete, it creates a Blob and triggers a programmatic download.

Need help integrating this into your project?

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

Hire DigitalCodeLabs