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.
Method 1: How to Trigger a File Download by Clicking an HTML Button? You need to utilize the <input> tag to create an HTML button and set its value to “Download”. The value is a user-defined attribute and can be set as per the user's wish.
Inside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the GET call of the JavaScript XmlHttpRequest call. Then inside the onload event handler, the received Byte Array (Binary Data) is converted to BLOB object and the File is downloaded in Browser.
In most browsers, clicking on the link will open the file directly in the browser. But, if you add the download attribute to the link, it will tell the browser to download the file instead. The download attribute works in all modern browsers, including MS Edge, but not Internet Explorer.
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
For the button you can do
<form method="get" action="file.doc"> <button type="submit">Download!</button> </form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With