19

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.

3
  • 1
    “For now i will have it in my local storage” - do you actually mean developer.mozilla.org/en-US/docs/Web/API/Window/localStorage, or are you just talking about the file being located in the server file system at the place where you described? Commented Feb 11, 2019 at 8:33
  • The file is located in the server file system at the place i described. Commented Feb 11, 2019 at 8:34
  • 1
    Okay, so then you just need to do things correctly, and it should work … You still need to use the href attribute of the link to refer to the file; download is an extra attribute you add. developer.mozilla.org/en-US/docs/Web/HTML/Element/a#Attributes Commented Feb 11, 2019 at 8:37

6 Answers 6

43

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

And if the file is in my local storage it works all the same ?
what exactly do you mean by local storage? aren't you using any local server ?
You can simplify the function in one line as: const downloadFile = (url, filename) => Object.assign(document.createElement('a'), { href: url, download: filename }).click();
ONLY suitable where the amount of data is less than the maximum allowable URI length (~2000) as explained by Paul Dixon's Jan 6, 2009 at 16:22
He probably meant: "What if the file is a blob"
22

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.

4 Comments

is there a way to set a file name this way?
@Zoid Since this directly opens an url, only the server can send approriate Headers to set a filename for the download.
Use the Content-Disposition header to set a file name (e.g., Content-Disposition: attachment; filename="sample.csv")
This might cause Session problems in mobile Safari Browsers, using window.open(url, '_parent'); resolved the issues.
3

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);
});

Comments

0

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.

Comments

-2

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();
}

1 Comment

This is just a copy of the accepted answer from 5+ years ago, with display: none added for some reason.
-5

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"});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.