AJAX - Handling File Downloads via AJAX

Introduction

AJAX is commonly used to retrieve data from a server without reloading the web page. While it is often associated with fetching JSON or text data, it can also be used to download files such as PDF documents, Excel spreadsheets, Word documents, images, ZIP archives, and CSV files. Unlike a normal hyperlink that triggers a browser download automatically, AJAX requires additional steps to process binary data and save it on the user's device.

Modern JavaScript provides the Blob object and object URLs, making it possible to download files received through AJAX efficiently. This technique offers better control over authentication, progress tracking, error handling, and dynamic file generation.


Why Download Files Using AJAX?

Traditional file downloads use a simple hyperlink:

<a href="report.pdf">Download Report</a>

Although this method is simple, it has limitations:

  • No progress indication.

  • Cannot easily attach authentication headers.

  • Difficult to validate user permissions before downloading.

  • Limited error handling.

  • Cannot dynamically generate files based on user selections.

AJAX overcomes these limitations by allowing developers to request the file programmatically before initiating the download.


Common File Types Downloaded Using AJAX

AJAX can download almost any file format.

Examples include:

  • PDF files

  • Microsoft Word documents

  • Excel spreadsheets

  • CSV reports

  • Images

  • Audio files

  • Video files

  • ZIP archives

  • JSON files

  • XML documents


How AJAX File Download Works

The overall process consists of several steps:

  1. User clicks the download button.

  2. AJAX sends a request to the server.

  3. Server generates or retrieves the requested file.

  4. Server returns the binary file data.

  5. JavaScript converts the received data into a Blob.

  6. A temporary URL is created.

  7. A hidden download link is generated.

  8. Browser downloads the file.

  9. Temporary resources are released.


Understanding Binary Data

Most files are binary data rather than plain text.

Examples:

Text Response

Hello Student

Binary Response

PDF
Image
Excel
ZIP
Video

Because binary data cannot be displayed as normal text, JavaScript stores it inside a Blob object.


What is a Blob?

Blob stands for Binary Large Object.

A Blob represents raw binary data that JavaScript can manipulate.

Examples:

  • PDF document

  • JPEG image

  • Excel file

  • ZIP archive

  • Audio recording

Instead of displaying the content, JavaScript stores it as a Blob until it is downloaded or processed.

Example:

const blob = new Blob(["Hello World"], {type: "text/plain"});

What is an Object URL?

A Blob cannot be downloaded directly.

JavaScript creates a temporary URL that points to the Blob.

Example:

const url = URL.createObjectURL(blob);

The URL might look like:

blob:https://example.com/8af45bc2-1a9d

This temporary URL exists only while the page is active.


Basic Download Process

Suppose a server provides a PDF report.

JavaScript can download it like this:

fetch("report.pdf")
.then(response => response.blob())
.then(blob => {

    const url = URL.createObjectURL(blob);

    const link = document.createElement("a");

    link.href = url;

    link.download = "AnnualReport.pdf";

    link.click();

    URL.revokeObjectURL(url);

});

Steps performed:

  • Fetch the file.

  • Convert response into Blob.

  • Create temporary URL.

  • Create hidden download link.

  • Simulate click.

  • Release memory.


Downloading Files Using XMLHttpRequest

Older applications often use XMLHttpRequest.

Example:

const xhr = new XMLHttpRequest();

xhr.open("GET", "report.pdf");

xhr.responseType = "blob";

xhr.onload = function(){

    const url = URL.createObjectURL(xhr.response);

    const link = document.createElement("a");

    link.href = url;

    link.download = "Report.pdf";

    link.click();

    URL.revokeObjectURL(url);

};

xhr.send();

Notice:

xhr.responseType = "blob";

Without this line, the browser treats the file as plain text.


Downloading an Image

Example:

fetch("photo.jpg")
.then(response => response.blob())
.then(blob=>{

    const url = URL.createObjectURL(blob);

    const a = document.createElement("a");

    a.href = url;

    a.download = "Vacation.jpg";

    a.click();

});

The image is downloaded instead of displayed.


Downloading a CSV Report

Many business applications generate CSV files.

Example:

fetch("/sales-report")
.then(response=>response.blob())
.then(blob=>{

    const url = URL.createObjectURL(blob);

    const link=document.createElement("a");

    link.href=url;

    link.download="Sales.csv";

    link.click();

});

The user receives the latest report without refreshing the page.


Downloading Files After Authentication

Many secure systems require authentication.

AJAX can include authorization headers.

Example:

fetch("/download/report",{

headers:{

Authorization:"Bearer YOUR_TOKEN"

}

})
.then(response=>response.blob())
.then(blob=>{

const url=URL.createObjectURL(blob);

const a=document.createElement("a");

a.href=url;

a.download="SecureReport.pdf";

a.click();

});

Only authorized users receive the file.


Displaying Download Progress

Large files may take time to download.

XMLHttpRequest supports progress tracking.

Example:

xhr.onprogress=function(event){

if(event.lengthComputable){

let percent=(event.loaded/event.total)*100;

console.log(percent);

}

}

Output:

15%

38%

62%

91%

100%

This information can update a progress bar.


Handling Download Errors

Problems may occur during downloading.

Examples:

  • File not found

  • Server unavailable

  • Network interruption

  • Permission denied

  • Authentication failure

Example:

fetch("report.pdf")

.then(response=>{

if(!response.ok){

throw new Error("Download failed");

}

return response.blob();

})

.catch(error=>{

console.log(error);

});

Proper error handling helps users understand why a download failed.


Releasing Object URLs

After downloading, the temporary URL should be removed.

Example:

URL.revokeObjectURL(url);

Benefits:

  • Frees memory.

  • Prevents memory leaks.

  • Improves browser performance.


Advantages of AJAX File Downloads

  • Downloads files without refreshing the page.

  • Supports secure authentication.

  • Enables progress tracking for large files.

  • Allows custom file names.

  • Provides detailed error handling.

  • Supports dynamic report generation.

  • Works with many file formats.

  • Enhances user experience.


Limitations

  • Slightly more complex than direct download links.

  • Very large files consume browser memory.

  • Some browsers impose security restrictions.

  • Temporary Blob objects use system resources.

  • Cross-Origin Resource Sharing (CORS) settings must allow the request when downloading from another domain.


Best Practices

  • Always validate user permissions on the server.

  • Use HTTPS for secure file transfers.

  • Release object URLs after use.

  • Display a loading indicator or progress bar for large downloads.

  • Handle network and server errors gracefully.

  • Assign meaningful file names using the download attribute.

  • Use fetch() for modern applications and XMLHttpRequest only when legacy browser support is required.

  • Compress large files when appropriate to reduce download time.

  • Ensure the server sends the correct Content-Type and Content-Disposition headers.

  • Test downloads across different browsers and devices.


Real-World Applications

AJAX file downloads are widely used in modern web applications:

  • Banking portals for downloading account statements.

  • E-commerce websites for invoices and order receipts.

  • Educational platforms for study materials and certificates.

  • Healthcare systems for medical reports.

  • Human Resource portals for salary slips and tax documents.

  • Government websites for application forms and certificates.

  • Business dashboards for exporting reports in Excel or PDF format.

  • Cloud storage platforms for downloading shared files.


Summary

Handling file downloads with AJAX allows web applications to deliver files seamlessly without reloading the page. By requesting files through AJAX, converting the response into a Blob, creating an object URL, and triggering a download programmatically, developers gain greater control over security, authentication, progress tracking, and error handling. This approach is particularly useful for applications that generate files dynamically, protect downloads with user authentication, or need to provide a smoother user experience than traditional download links. Following best practices such as releasing object URLs, validating permissions, and handling errors ensures efficient, secure, and reliable file downloads.