How to trigger a file download when clicking an HTML button or 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:
Download!

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

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.

Solutions/Answers:

Solution 1:

For the button you can do

<form method="get" action="file.doc">
   <button type="submit">Download!</button>
</form>

Solution 2:

I have done some research and found the best answer. You can trigger a download by using the new HTML5 download attribute.

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

Where :

  • path_to_file is either an absolute or relative path,
  • proposed_file_name the filename to save to (can be blank, then defaults to the actual filename).

Hope this is helpful.

Whatwg Documentation

Caniuse

Solution 3:

With jQuery:

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

Solution 4:

HTML:

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

Solution 5:

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

Solution 6:

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)