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

Viewed 1468436

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.

25 Answers

Hello I just include the word 'download' and works well.

<a href="file.pdf" download>Download</a>

So in javascript you can use the follow:

function onStartedDownload(id) {
  console.log(`Started downloading: ${id}`);
}

function onFailed(error) {
  console.log(`Download failed: ${error}`);
}

var downloadUrl = "https://example.org/image.png";

var downloading = browser.downloads.download({
  url : downloadUrl,
  filename : 'my-image-again.png',
  conflictAction : 'uniquify'
});

downloading.then(onStartedDownload, onFailed);

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

const download = document.getElementById("fileRequest");

download.addEventListener('click', request);

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

In my testing the following works for all file types and browsers as long as you use a relative link:

<a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>
  • /assets/hello.txt is just a relative path on my site. Change it to your own relative path.
  • my_file.txt is the name you want the file to be called when it is downloaded.

Explanation

I noticed there were comments under a lot of the answers that said the browser would just try to open the file itself rather than downloading it depending on the file type. I discovered this to be true.

I made two buttons to test it out using two different methods:

enter image description here

<button onclick="window.location.href='/assets/hello.txt';">Download 1</button>

<a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>

Notes:

  • Button 1 opened the text file in a new browser tab. However, Button 1 would download the file for file types that it couldn't open itself (for example, .apk files).
  • Button 2 downloaded the text file. However, Button 2 only downloaded the file if the path was relative. When I changed the path to an absolute path, then the browser opened it in a new tab.

I tested this on Firefox, Safari, and Chrome.

<a href="file.doc"><button>Download!</button></a>
This will download the file as .doc file extension is not supported to be opened in browser.
One of the simplest way for button and the text-decoration will help to alter or to remove the text decoration of the link.

all you need to do is add Download after the file name which you have entered:

Before:

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

After

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

Make sure the download is written with a capital letter otherwise it's not gonna work.

Not really an answer to the original question but it may help others which face similar situations as myself.

If the file you want to download is not hosted on the same origin but you want to be able to download it, you can do that with the Content-Disposition header. Make sure the server includes the header when responding to requests of the file.

Setting a value like Content-Disposition: attachment will ensure that the file will be downloaded instead of viewed in the browser.

A simple <a href="http://www.notMyOrigin.com/file.txt">Download</a> pointing to your file should download it in this case.

If you want

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

for the ability to download files that would be rendered by the browser otherwise, But still want a neat javascript function to use in a button; you can have an invisible link in html and click it in javascript.

function download_file() {
  document.getElementById("my_download").click()
}
<a id="my_download" href="path_to_file" download="file_name" style="display:none;"></a>

<button onClick="download_file()">Download!!!</button>

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.

For the react users out there, I think this is a pretty clean way to go about it:

import React, {useRef} from 'react';

const DlButton = ({link}) => {
    const dlRef = useRef();
    const dlHandler = () => dlRef.current.click();

    return (
        <div>
          <button type="button" onClick={dlHandler}> 
              Download File
          </button>
          <a href={link} ref={dlRef}/>
        </div>
    );
}

Basically you create a link with no content (won't be viewed by user). Then you simply click that link when the user clicks the button.

Related