How to trigger a file download when clicking an HT

2018-12-31 15:15发布

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.

18条回答
心情的温度
2楼-- · 2018-12-31 15:55

You can hide the download link and make the button click it.

<button onclick="document.getElementById('link').click()">Download!</button>
<a id="link" href="file.doc" download hidden></a>
查看更多
心情的温度
3楼-- · 2018-12-31 15:57

I think this is the solution you were looking for

<button type="submit" onclick="window.location.href='file.doc'">Download!</button>

I hade a case where my Javascript generated a CSV file. Since there is no remote URL to download it I use the following implementation.

downloadCSV: function(data){
    var MIME_TYPE = "text/csv";

    var blob = new Blob([data], {type: MIME_TYPE});
    window.location.href = window.URL.createObjectURL(blob);
}
查看更多
呛了眼睛熬了心
4楼-- · 2018-12-31 15:58

For the button you can do

<form method="get" action="file.doc">
   <button type="submit">Download!</button>
</form>
查看更多
像晚风撩人
5楼-- · 2018-12-31 16:02

Another way of doing in case you have a complex URL such as file.doc?foo=bar&jon=doe is to add hidden field inside the form

<form method="get" action="file.doc">
  <input ty='hidden' name='foo' value='bar'/>
  <input ty='hidden' name='john' value='doe'/>
  <button type="submit">Download Now</button>
</form>

inspired on @Cfreak answer which is not complete

查看更多
永恒的永恒
6楼-- · 2018-12-31 16:05

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

查看更多
余欢
7楼-- · 2018-12-31 16:09

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>

查看更多
登录 后发表回答