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

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

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

其他回答

你可以用隐形iframe的“trick”来实现。当你将“src”设置为它时,浏览器的反应就像你点击了一个具有相同“href”的链接。与表单解决方案相反,它允许您嵌入额外的逻辑,例如在超时后激活下载,当某些条件满足时等等。

它也非常安静,没有闪烁的新窗口/标签时使用window.open。

HTML:

<iframe id="invisible" style="display:none;"></iframe>

Javascript:

function download() {
    var iframe = document.getElementById('invisible');
    iframe.src = "file.doc";
}

是什么:

<input type="button" value="Download Now!" onclick="window.location = 'file.doc';">

这并不是对最初问题的答案,但它可能会帮助那些面临与我类似情况的人。

如果您想下载的文件不在同一个源文件上,但您希望能够下载它,您可以使用Content-Disposition头文件来完成。确保服务器在响应文件请求时包含头文件。

设置如下值 内容处理:附件将确保文件将被下载,而不是在浏览器中查看。

一个简单的< A href="http://www.notMyOrigin.com/file.txt">Download</ A >指向你的文件应该在这种情况下下载它。

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

你所需要做的就是在你输入的文件名后面加上下载:

之前:

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

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

确保下载用大写字母书写,否则它将无法工作。