[javascript] How to trigger a file download when clicking an HTML button or JavaScript

This is crazy but I don't know how to do this, and because of how common the words are, it's hard to find what I need on search engines. I'm thinking this should be an easy one to answer.

I want a simple file download, that would do the same as this:

<a href="file.doc">Download!</a>

But I want to use an HTML button, e.g. either of these:

<input type="button" value="Download!">
<button>Download!</button>

Likewise, is it possible to trigger a simple download via JavaScript?

$("#fileRequest").click(function(){ /* code to download? */ });

I'm definitely not looking for a way to create an anchor that looks like a button, use any back-end scripts, or mess with server headers or mime types.

This question is related to javascript html download

The answer is


you can add tag without any text but with link. and when you click the button like you have in code , just run the $("yourlinkclass").click() function.


You can hide the download link and make the button click it.

<button onclick="document.getElementById('link').click()">Download!</button>
<a id="link" href="file.doc" download hidden></a>

What about:

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">

There is a difference between loading a file and downloading a file. The following html code loads a file:

<a href="http://www.fbi.gov/top-secret.pdf">loading on the same tab</a>

After clicking on this link, your current tab will be replaced with the pdf-file that can then be downloaded. On right-clicking on this link, you can choose the menu item save link as for downloading the file directly. If you wish to obtain a save as dialog on clicking on such a link, you might want to take the following code:

<a href="http://www.fbi.gov/top-secret.pdf?download=1">save as...</a>

Your browser will download this file immediately if you choose to use a download directory in your options. Otherwise, your browser will be offering a save as-dialog.

You can also choose a button for downloading:

<button type="submit" onclick="window.open('http://www.fbi.gov/top-secret.pdf?download=1')">
    save as...
</button>

If you wish to load the link on a new tab, you take

<a href="http://www.fbi.gov/top-secret.pdf" target="_blank">loading on a new tab</a>

A form element does not heed the directive ?download=1. It only heeds the directive target="_blank":

<form method="get" action="http://www.fbi.gov/top-secret.pdf" target="_blank">
    <button type="submit">loading on a new tab</button>
</form>

HTML:

<button type="submit" onclick="window.open('file.doc')">Download!</button>

If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:

<div onClick=(()=>{downloadjs(url, filename)})/>

*it's jsx/react syntax, but can be used in pure html

Note: Edited to fix layout issue above


For me ading button instead of anchor text works really well.

<a href="file.doc"><button>Download!</button></a>

It might not be ok by most rules, but it looks pretty good.


The solution I have come up with is that you can use download attribute in anchor tag but it will only work if your html file is on the server. but you may have a question like while designing a simple html page how can we check that for that you can use VS code live server or bracket live server and you will see your download attribute will work but if you will try to open it simply by just double clicking html page it open the file instead of downloading it. conclusion: attribute download in anchor tag only works if your html file is no server.


This is what finally worked for me since the file to be downloaded was determined when the page is loaded.

JS to update the form's action attribute:

function setFormAction() {
    document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
}

Calling JS to update the form's action attribute:

<body onLoad="setFormAction();">

Form tag with the submit button:

<form method="get" id="myDownloadButtonForm" action="">
    Click to open document:  
    <button type="submit">Open Document</button>
</form>

The following did NOT work:

<form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">

You can do it with "trick" with invisible iframe. When you set "src" to it, browser reacts as if you would click a link with the same "href". As opposite to solution with form, it enables you to embed additional logic, for example activating download after timeout, when some conditions are met etc.

It is also very silient, there's no blinking new window/tab like when using window.open.

HTML:

<iframe id="invisible" style="display:none;"></iframe>

Javascript:

function download() {
    var iframe = document.getElementById('invisible');
    iframe.src = "file.doc";
}

download attribute do it

 <a class="btn btn-success btn-sm" href="/file_path/file.type" download>
     <span>download </span>&nbsp;<i class="fa fa-download"></i>
 </a>

You can trigger a download with the HTML5 download attribute.

<a href="path_to_file" download="proposed_file_name">Download</a>

Where:

  • path_to_file is a path that resolves to an URL on the same origin. That means the page and the file must share the same domain, subdomain, protocol (HTTP vs. HTTPS), and port (if specified). Exceptions are blob: and data: (which always work), and file: (which never works).
  • proposed_file_name is the filename to save to. If it is blank, the browser defaults to the file's name.

Documentation: MDN, HTML Standard on downloading, HTML Standard on download, CanIUse


Old thread but it's missing a simple js solution:

let a = document.createElement('a')
a.href = item.url
a.download = item.url.split('/').pop()
document.body.appendChild(a)
a.click()
document.body.removeChild(a)

With jQuery:

$("#fileRequest").click(function() {
    // // hope the server sets Content-Disposition: attachment!
    window.location = 'file.doc';
});

Anywhere between your <body> and </body> tags, put in a button using the below code:

<button>
    <a href="file.doc" download>Click to Download!</a>
</button>

This is sure to work!


Another way of doing in case you have a complex URL such as file.doc?foo=bar&jon=doe is to add hidden field inside the form

<form method="get" action="file.doc">
  <input type="hidden" name="foo" value="bar" />
  <input type="hidden" name="john" value="doe" />
  <button type="submit">Download Now</button>
</form>

inspired on @Cfreak answer which is not complete


If your looking for a vanilla JavaScript (no jQuery) solution and without using the HTML5 attribute you could try this.

_x000D_
_x000D_
const download = document.getElementById("fileRequest");_x000D_
_x000D_
download.addEventListener('click', request);_x000D_
_x000D_
function request() {_x000D_
    window.location = 'document.docx';_x000D_
}
_x000D_
.dwnld-cta {_x000D_
    border-radius: 15px 15px;_x000D_
    width: 100px;_x000D_
    line-height: 22px_x000D_
}
_x000D_
<h1>Download File</h1>_x000D_
<button id="fileRequest" class="dwnld-cta">Download</button>
_x000D_
_x000D_
_x000D_


Bootstrap Version

<a class="btn btn-danger" role="button" href="path_to_file"
   download="proposed_file_name">
  Download
</a>

Documented in Bootstrap 4 docs, and works in Bootstrap 3 as well.


I think this is the solution you were looking for

<button type="submit" onclick="window.location.href='file.doc'">Download!</button>

I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.

downloadCSV: function(data){
    var MIME_TYPE = "text/csv";

    var blob = new Blob([data], {type: MIME_TYPE});
    window.location.href = window.URL.createObjectURL(blob);
}

If you use the <a> tag, do not forget to use the entire url which leads to the file -- i.e.:

<a href="http://www.example.com/folder1/file.doc">Download</a>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to download

how to download file in react js How do I download a file with Angular2 or greater Unknown URL content://downloads/my_downloads python save image from url How to download a file using a Java REST service and a data stream How to download file in swift? Where can I download Eclipse Android bundle? How to download image from url android download pdf from url then open it with a pdf reader Flask Download a File