Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 705
brentonstrine Avatar asked Jul 23 '12 21:07

brentonstrine


People also ask

How do I trigger a download in HTML?

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.

How do you automatically download a file in JavaScript?

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.

How do I force a browser to download a file?

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.


2 Answers

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

like image 60
Joe Pigott Avatar answered Sep 29 '22 18:09

Joe Pigott


For the button you can do

<form method="get" action="file.doc">    <button type="submit">Download!</button> </form> 
like image 29
Cfreak Avatar answered Sep 29 '22 18:09

Cfreak