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.
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:
Javascript:
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:
Calling JS to update the form's action attribute:
Form tag with the submit button:
The following did NOT work:
Old thread but it's missing a simple js solution:
It doesn't seem to work in Safari, but it did work in Chrome. Also, changing the href attribute of the link once the user clicked it seemed to make it work in older versions of IE, but not in the latest versions of IE or Edge.
Anywhere between your
<body>
and</body>
tags, put in a button using the below code:This is sure to work!
If you can't use form, another approach with downloadjs fit nice. Downloadjs use blob and html 5 file API under the hood:
{downloadjs(url, filename)})/>
*it's jsx/react syntax, but can be used in pure html