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

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

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

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

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

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

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

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


当前回答

你可以用隐形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";
}

其他回答

HTML:

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

jQuery:

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

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

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

<button>
    <a href="file.doc" download>Click to Download!</a>
</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);