Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download file with javascript?

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.

like image 804
Bercovici Adrian Avatar asked Feb 11 '19 08:02

Bercovici Adrian


2 Answers

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();
}
like image 199
saibbyweb Avatar answered Sep 21 '22 01:09

saibbyweb


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.

like image 36
mondjunge Avatar answered Sep 20 '22 01:09

mondjunge