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

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

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

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

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

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

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

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


当前回答

jQuery:

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

其他回答

这是最终为我工作,因为要下载的文件是在页面加载时确定的。

JS来更新表单的action属性:

function setFormAction() {
    document.getElementById("myDownloadButtonForm").action = //some code to get the filename;
}

调用JS来更新表单的action属性:

<body onLoad="setFormAction();">

表单标签与提交按钮:

<form method="get" id="myDownloadButtonForm" action="">
    Click to open document:  
    <button type="submit">Open Document</button>
</form>

以下是没有工作:

<form method="get" id="myDownloadButtonForm" action="javascript:someFunctionToReturnFileName();">

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.

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

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

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

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

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

如果你愿意

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

对于下载文件的能力,否则将由浏览器渲染,但仍然想要一个整洁的javascript函数在按钮中使用;你可以在HTML中有一个看不见的链接,然后在javascript中点击它。

函数download_file() { . getelementbyid(“my_download”).click () } <a id="my_download" href="path_to_file" download="file_name" style="display:none;" > < / > <按钮onClick = " download_file() " >下载! !< / >按钮