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:48

If you use the <a> tag, do not forget to use the entire url which leads to the file -- i.e.:

<a href="http://www.example.com/folder1/file.doc">Download</a>
查看更多
几人难应
3楼-- · 2018-12-31 15:49

HTML:

<button type="submit" onclick="window.open('file.doc')">Download!</button>
查看更多
妖精总统
4楼-- · 2018-12-31 15:52

With jQuery:

$("#fileRequest").click(function() {
    // // hope the server sets Content-Disposition: attachment!
    window.location = 'file.doc';
});
查看更多
冷夜・残月
5楼-- · 2018-12-31 15:52

What about:

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">
查看更多
泛滥B
6楼-- · 2018-12-31 15:52

For me ading button instead of anchor text works really well.

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

It might not be ok by most rules, but it looks pretty good.

查看更多
公子世无双
7楼-- · 2018-12-31 15:53

Bootstrap Version

<a class="btn btn-danger" role="button" href="path_to_file"
   download="proposed_file_name">
  Download
</a>

Documented in Bootstrap 4 docs, and works in Bootstrap 3 as well.

查看更多
登录 后发表回答