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

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

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

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

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

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

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

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


当前回答

HTML:

<button type="submit" onclick="window.open('file.doc')">Download!</button>

其他回答

HTML:

<button type="submit" onclick="window.open('file.doc')">Download!</button>

你好,我只是包括“下载”这个词,工作得很好。

<a href="file.pdf" download>Download</a>

所以在javascript中你可以使用以下代码:

function onStartedDownload(id) {
  console.log(`Started downloading: ${id}`);
}

function onFailed(error) {
  console.log(`Download failed: ${error}`);
}

var downloadUrl = "https://example.org/image.png";

var downloading = browser.downloads.download({
  url : downloadUrl,
  filename : 'my-image-again.png',
  conflictAction : 'uniquify'
});

downloading.then(onStartedDownload, onFailed);

如果你正在寻找一个普通的JavaScript(而不是jQuery)解决方案,并且不使用HTML5属性,你可以试试这个。

const download = document.getElementById("fileRequest"); 下载。addEventListener(“点击”,请求); 函数请求(){ 窗口。Location = 'document.docx'; } .dwnld-cta { 边框半径:15px 15px; 宽度:100 px; 行高:22 px } 下载文件< h1 > < / h1 > <button id="fileRequest" class="dwnld-cta">Download</button> .

jQuery:

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

如果你愿意

<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() " >下载! !< / >按钮