单击 HTML 按钮或 JavaScript 时如何触发文件下载 [英] How to trigger a file download when clicking an HTML button or JavaScript

查看:25
本文介绍了单击 HTML 按钮或 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆