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

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

<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.

其他回答

如果你有一个复杂的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的不完整的答案

对我来说,点击按钮而不是锚文本工作得很好。

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

在大多数规则下,这可能是不合适的,但它看起来相当不错。

在我的测试中,以下内容适用于所有文件类型和浏览器,只要你使用相对链接:

<a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>

/assets/hello.txt只是我网站上的一个相对路径。将其更改为您自己的相对路径。 My_file.txt是您希望在下载时调用该文件的名称。

解释

我注意到很多答案下面都有评论说浏览器会根据文件类型来尝试打开文件,而不是下载文件。我发现这是真的。

我用两种不同的方法制作了两个按钮进行测试:

<button onclick="window.location.href='/assets/hello.txt';">Download 1</button>

<a href="/assets/hello.txt" download="my_file.txt"><button>Download 2</button></a>

注:

按钮1在一个新的浏览器选项卡中打开文本文件。但是,Button 1会下载它自己无法打开的文件类型(例如.apk文件)。 按钮2下载文本文件。但是,如果路径是相对的,按钮2只下载文件。当我将路径更改为绝对路径时,浏览器会在一个新选项卡中打开它。

我在Firefox、Safari和Chrome上进行了测试。

引导程序版本

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

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

我觉得这就是你想要的解决方案

<button type="submit" onclick="window.location.href='file.doc'">Download!</button>

我有一个案例,我的Javascript生成了一个CSV文件。由于没有远程URL来下载它,我使用以下实现。

downloadCSV: function(data){
    var MIME_TYPE = "text/csv";

    var blob = new Blob([data], {type: MIME_TYPE});
    window.location.href = window.URL.createObjectURL(blob);
}