Why Download Files from Websites?
Allowing users to download files from your web application opens up useful possibilities. You may want visitors to access PDF reports, export data in CSV format, download invoices or confirmations, and more.
With some JavaScript code, handling file downloads is straightforward. In this guide, we‘ll explore different techniques for triggering browser file saves.
Downloading Files with Vanilla JS
The simplest approach uses plain JavaScript to set the browser‘s location to a file URL.
Here‘s a quick demo with a button click handler:
downloadBtn.addEventListener(‘click‘, () => {
const filename = ‘example.pdf‘;
// Set MIME type
const mimeType = ‘application/pdf‘;
// Construct URL
const fileUrl = `files/${filename}`;
// Set location
window.location.href = fileUrl;
});
This works by redirecting the browser to a file resource on the server, triggering the "Save As" dialog.
Some key points:
- We build the file URL from a filename constant
- It‘s good practice to explicitly set the MIME type first
- No server-side code is needed if the files already exist
While simple, the downside is it navigates away from the current page. Next we‘ll see how to solve that…
Downloading without Leaving the Page
To stay on the same page, we need to utilize some browser API magic:
const downloadFile = async () => {
// Fetch file content
const response = await fetch(‘file.zip‘);
const blob = await response.blob();
// Create file link
const link = document.createElement(‘a‘);
link.href = URL.createObjectURL(blob);
// Trigger download
link.download = ‘file.zip‘;
document.body.appendChild(link);
link.click();
link.remove();
}
By fetching the file data into a blob, we can construct a temporary link to trigger the download.
Key aspects:
- The fetch call retrieves the file content
- We convert the response into a Blob object
- Create an anchor link dynamically and set the href
- Give the link a download attribute with the filename
- Append link to DOM, trigger click, then remove
This allows the download without leaving the page!
Downloading Files with jQuery AJAX
For even more control, jQuery AJAX requests can handle file downloads too:
$(‘#download‘).click(function() {
$.ajax({
url: ‘/files/report.pdf‘,
method: ‘GET‘,
xhrFields: {
responseType: ‘blob‘
},
success: function(data) {
var a = document.createElement(‘a‘);
var url = window.URL.createObjectURL(data);
a.href = url;
a.download = ‘report.pdf‘;
document.body.append(a);
a.click();
a.remove();
window.URL.revokeObjectURL(url);
}
});
});
Here jQuery fetches the file content, and we once again construct a temp link with a set download filename.
Benefits over vanilla JS:
- Handles errors automatically
- Can integrate with UI libraries like Bootstrap
- Support timeouts, caching, headers etc
This covers the basics of forcing file downloads with JavaScript and jQuery. Read on for more details…