且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何强制/允许用户下载多个文件? (客户端)

更新时间:2021-06-30 21:46:25

虽然它不应该有可能,我设法在Chrome中做了一些巫术。首先,您需要将下载 attrbute设置为所有链接f.ex:

Although it shouldn’t be possible, I managed to do this in Chrome with some sorcery. First you need to set the download attrbute to all your links f.ex:

<a href="http://example.com/image1.jpg" download>download</a>
<a href="http://example.com/image2.jpg" download>download</a>

然后创建一个合成点击功能:

Then create a synthetic click function:

function makeClick(element) {
    var evt = element.ownerDocument.createEvent('MouseEvents');
    evt.initMouseEvent('click', true, true,
        element.ownerDocument.defaultView, 1, 0, 0, 0, 0, false,
        false, false, false, 1, null);
    element.dispatchEvent(evt);
}​

然后只需循环链接并调用它:

Then just loop through your links and call it:

var links = document.getElementsByTagName('a');
for(var i=0;i<links.length; i++) {
    makeClick(links[i]);
}

这是一个演示: http://jsfiddle.net/37pFC/

在Chrome中,您会收到类似警告的警告这个网站要你下载多个文件。允许吗?但这可能是可以控制的。

In Chrome you will get a warning saying something like "This site wants you to download multiple files. Allow?" but this might be manageable.

免责声明:我没有在其他浏览器中尝试过,我认为它不是跨浏览器友好的。

Disclaimer: I havent tried in other browsers, and I don’t think it’s very cross-browser friendly.