how to download a file using javascript
Downloading a file using JavaScript can be accomplished in several ways, depending on the context and the source of the file. Here are a few common methods:
<a>
) ElementYou can create an anchor element and programmatically trigger a click event to download a file.
function downloadFile(url, filename) {
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
// Usage
downloadFile('https://example.com/file.pdf', 'file.pdf');
If you have the file data as a Blob, you can create a URL for it and download it.
function downloadBlob(blob, filename) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
// Usage
const blob = new Blob(['Hello, world!'], { type: 'text/plain' });
downloadBlob(blob, 'hello.txt');
You can use the Fetch API to download a file and then use the Blob method to save it.
async function downloadFile(url, filename) {
const response = await fetch(url);
const blob = await response.blob();
const a = document.createElement('a');
const urlBlob = URL.createObjectURL(blob);
a.href = urlBlob;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(urlBlob);
}
// Usage
downloadFile('https://example.com/file.pdf', 'file.pdf');
For more advanced use cases, you might want to use a library like FileSaver.js.
First, include the FileSaver.js library in your project:
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.5/FileSaver.min.js"></script>
Then, use it to save files:
function downloadFile(url, filename) {
fetch(url)
.then(response => response.blob())
.then(blob => {
saveAs(blob, filename);
});
}
// Usage
downloadFile('https://example.com/file.pdf', 'file.pdf');
Choose the method