You cannot use the Fetch/Blob method. You will have to rely on a standard window.open(url, '_blank') , which may open the file in the browser (like a PDF or Image) rather than downloading it. Summary Table: Which method should you use? Recommended Method Same-domain, small files Anchor tag with download attribute Cross-domain (with CORS) Fetch API + Blob Large files (>100MB) Streams API or StreamSaver.js Data generated in JS (JSON/CSV) Blob + URL.createObjectURL Pro-Tip: Content-Disposition
Clean and requires no libraries. Cons: The download attribute is often ignored by browsers if the file is on a different domain (Cross-Origin), causing the browser to just open the file in a new tab instead. 2. The Robust Way: Fetch API + Blob
If you need to download files from a different origin or need more control (like adding headers or tracking progress), using fetch() to get the data as a is the professional standard. javascript javascript download files from url
To handle this, you should use the or a library like StreamSaver.js. This allows you to write the data to the hard drive as it's being downloaded, rather than waiting for the whole file to finish. 4. Important: Dealing with CORS
function downloadFromUrl(url, filename) // Usage downloadFromUrl('https://example.com', 'May_Report.pdf'); Use code with caution. You cannot use the Fetch/Blob method
async function forceDownload(url, filename) try const response = await fetch(url); if (!response.ok) throw new Error('Network response was not ok'); // Convert the response to a Blob (Binary Large Object) const blob = await response.blob(); // Create a local URL for the Blob const blobUrl = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.href = blobUrl; a.download = filename; document.body.appendChild(a); a.click(); // Cleanup: remove element and revoke the ObjectURL to save memory a.remove(); window.URL.revokeObjectURL(blobUrl); catch (error) console.error('Download failed:', error); // Usage forceDownload('https://example.com', 'archive.zip'); Use code with caution.
The server hosting the file must include the header: Access-Control-Allow-Origin: * (or your specific domain). Recommended Method Same-domain, small files Anchor tag with
In the modern web, downloading files directly from a URL via JavaScript is a fundamental requirement for everything from exporting CSV reports to saving user-generated images. While it sounds simple, the "best" method depends heavily on whether the file is on your server (same-origin) or a different one (cross-origin).