如何在单击html按钮或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:
<a href="file.doc">Download!</a>
但是我想使用HTML按钮,例如以下任一项:
But I want to use an HTML button, e.g. either of these:
<input type="button" value="Download!">
<button>Download!</button>
同样,是否可以通过Javascript触发简单的下载?
Likewise, is it possible to trigger a simple download via Javascript?
$("#fileRequest").click(function(){ /* code to download? */ });
我绝对不会寻找一种创建锚点的方法看起来像一个按钮,使用任何后端脚本,或混乱服务器头或MIME类型。
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.
推荐答案
可以做
<form method="get" action="file.doc">
<button type="submit">Download!</button>
</form>
这篇关于如何在单击html按钮或javascript时触发文件下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!