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

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

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

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

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

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

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

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


当前回答

引导程序版本

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

在Bootstrap 4文档中有记录,并且在Bootstrap 3中也有工作。

其他回答

对于按钮可以这样做

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

jQuery:

$("#fileRequest").click(function() {
    // hope the server sets Content-Disposition: attachment!
    window.location = 'file.doc';
});

在<body>和</body>标签之间的任何地方,使用下面的代码放入一个按钮:

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

这一定有用!

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.

您可以使用HTML5 download属性触发下载。

<a href="path_to_file" download="proposed_file_name">Download</a>

地点:

path_to_file是解析为同一源上的URL的路径。这意味着页面和文件必须共享相同的域、子域、协议(HTTP vs. HTTPS)和端口(如果指定了)。例外是blob:和data:(总是工作)和file:(从不工作)。 Proposed_file_name是要保存到的文件名。如果它为空,浏览器默认为文件的名称。

文档:MDN, HTML标准下载,HTML标准下载,CanIUse