Reputation: 9360
I want to be able to download a given file when pressing a button.The file will be provided via an API
call.For now, I will have it in my local storage.
So my folder is something like :
rootFolder
-JS file
-HTML file
-download file (`sample.csv`)
How can I create a download link
?
I have tried so far with :
<a download="sample.csv"></a>
I have also tried using an onclick
event:
<a download="sample.csv" onclick="download()"></a>
function download|(){
.....code that calls the `api`
}
I do not know how these 2 fit: the download
API if there is one and the click
event handler if you plan to do additional logic when downloading.
Upvotes: 19
Views: 84573
Reputation: 638
I came across this recently and want to share a complete example that works in all modern browsers.
document.getElementById('downloadButton').addEventListener('click', () => {
// File content and filename
const fileContent = "This is an example file content.";
const fileName = "example.txt";
// Create a Blob object with the file content
const blob = new Blob([fileContent], { type: 'text/plain' });
// Create a temporary link element
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
// Programmatically click the link to trigger the download
link.click();
// Clean up the URL object
URL.revokeObjectURL(link.href);
});
Upvotes: 0
Reputation: 1
You can use this to download images and other files:
function downloadImg(url, name) {
let link = document.createElement('a');
link.download = name;
link.href = url;
link.style.display = 'none';
link.click();
}
Upvotes: -2
Reputation: 9
You can create a Chrome's extension. You must have the download permission, in your "manifest.json". I put the code in the "browser_action" files, in the manifest.
chrome.downloads.download({url:"https://stackoverflow.com/questions/54626186/how-to-download-file-with-javascript"});
Upvotes: -6
Reputation: 1239
since the answer from @saibbyweb does not work in all browsers as I write this, i recommend an other but similar solution, tested and working in latest (as of writing) Firefox, Chrome, Opera, Edge, Safari, mobile Safari, mobile Chrome:
function downloadUrl(url){
window.open(url, '_self');
}
Needless to say you could also open links in new Tabs with _blank instead of _self, but you potentially startle Popup-Blockers by opening new tabs/windows with Javascript.
Upvotes: 21
Reputation: 456
You can do it via HTML <a href="/path/to/sample.csv"></a>
, but if you have to do it in JS there is https://github.com/eligrey/FileSaver.js/ library.
Upvotes: 0
Reputation: 3244
You can provide the link to this function to download the file :
function downloadURI(uri, name)
{
var link = document.createElement("a");
link.download = name;
link.href = uri;
link.click();
}
Upvotes: 42