How to Download File Using Fetch in JavaScript
Use the
fetch API to request the file, then convert the response to a Blob. Create a temporary link with URL.createObjectURL and trigger a click to download the file.Syntax
The basic syntax to download a file using fetch involves fetching the file URL, converting the response to a Blob, creating a temporary link, and triggering a download.
fetch(url): Requests the file from the server.response.blob(): Converts the response data into a binary large object.URL.createObjectURL(blob): Creates a temporary URL for the blob.link.download: Sets the filename for the downloaded file.link.click(): Simulates a click to start the download.
javascript
fetch('file_url') .then(response => response.blob()) .then(blob => { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'filename.ext'; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); });
Example
This example downloads an image file from a URL and saves it as sample-image.png on your computer.
javascript
async function downloadFile() { try { const response = await fetch('https://via.placeholder.com/150'); if (!response.ok) throw new Error('Network response was not ok'); const blob = await response.blob(); const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'sample-image.png'; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); console.log('Download started'); } catch (error) { console.error('Download failed:', error); } } downloadFile();
Output
Download started
Common Pitfalls
Common mistakes when downloading files with fetch include:
- Not converting the response to a
Blob, which causes the download to fail. - Forgetting to set the
downloadattribute on the link, so the file saves with a default or no name. - Not revoking the object URL after download, which can cause memory leaks.
- Trying to download cross-origin files without proper CORS headers, leading to errors.
javascript
/* Wrong way: Missing blob conversion and download attribute */ fetch('https://example.com/file.pdf') .then(response => response.text()) // Incorrect: should be blob() .then(data => { const link = document.createElement('a'); link.href = data; // This won't work as expected document.body.appendChild(link); link.click(); link.remove(); }); /* Right way: Convert to blob and set download attribute */ fetch('https://example.com/file.pdf') .then(response => response.blob()) .then(blob => { const url = URL.createObjectURL(blob); const link = document.createElement('a'); link.href = url; link.download = 'file.pdf'; document.body.appendChild(link); link.click(); link.remove(); URL.revokeObjectURL(url); });
Quick Reference
Remember these key points when downloading files with fetch:
- Always convert response to
Blobfor binary files. - Use
link.downloadto set the filename. - Clean up with
URL.revokeObjectURLafter download. - Handle errors with
try/catchor.catch().
Key Takeaways
Use fetch with response.blob() to get the file data correctly.
Create a temporary link with URL.createObjectURL and set the download attribute.
Always revoke the object URL after the download to free memory.
Handle network errors to avoid silent failures.
Cross-origin files require proper CORS headers to download successfully.