这很疯狂,但我不知道怎么做,因为这些词太常见了,在搜索引擎上很难找到我需要的东西。我想这个问题应该很容易回答。

我想要一个简单的文件下载,这将与此相同:

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

但是我想使用一个HTML按钮,例如:

<input type="button" value="Download!">
<button>Download!</button>

同样,是否有可能通过JavaScript触发一个简单的下载?

$("#fileRequest").click(function(){ /* code to download? */ });

我绝对不会寻找一种方法来创建一个看起来像按钮的锚,使用任何后端脚本,或混乱的服务器头或mime类型。


当前回答

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.

其他回答

如果你不能使用表单,另一种方法downloadjs很适合。Downloadjs在底层使用blob和html 5文件API:

<div onClick=(()=>{downloadjs(url, filename)})/>

*它是jsx/react语法,但可以在纯HTML中使用

如果你使用<a>标记,不要忘记使用指向文件的整个url——即:

<a href="http://www.example.com/folder1/file.doc">Download</a>

< a href = " file.doc " > < >按钮下载!< /按钮> < / > 这将下载文件作为。doc文件扩展名不支持在浏览器中打开。 其中一个最简单的方法按钮和文字装饰将有助于改变或删除链接的文字装饰。

对于按钮可以这样做

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

如果你有一个复杂的URL,比如file。doc?Foo =bar&jon=doe是在表单中添加隐藏字段

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

灵感来自@Cfreak的不完整的答案