我在这里指定了一个非常类似的需求。

我需要有用户的浏览器手动启动下载时$('a#someID').click();

但是我不能用窗户。Href方法,因为它将当前页面内容替换为您试图下载的文件。

相反,我想在新窗口/标签中打开下载。这怎么可能呢?


当前回答

使用iframe的简单示例

function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

然后在任何你想要的地方调用这个函数:

downloadURL(“path / to /我的文件”);

其他回答

我建议使用下载属性而不是jQuery:

<a href="your_link" download> file_name </a>

这将下载您的文件,而不需要打开它。

function downloadURI(uri, name) 
{
    var link = document.createElement("a");
    // If you don't know the name or want to use
    // the webserver default set name = ''
    link.setAttribute('download', name);
    link.href = uri;
    document.body.appendChild(link);
    link.click();
    link.remove();
}

检查您的目标浏览器是否能够顺利运行上面的代码片段:http://caniuse.com/#feat=download

我知道我迟到了,但我想分享我的解决方案,这是上面Imagine Breaker解决方案的变化。我试着用他的方法,因为他的方法对我来说是最简单易行的。但就像其他人说的那样,它不适合某些浏览器,所以我使用jquery对它进行了一些修改。

希望这能帮助到那里的人。

function download(url) {
  var link = document.createElement("a");
  $(link).click(function(e) {
    e.preventDefault();
    window.location.href = url;
  });
  $(link).click();
}

使用iframe的简单示例

function downloadURL(url) {
    var hiddenIFrameID = 'hiddenDownloader',
        iframe = document.getElementById(hiddenIFrameID);
    if (iframe === null) {
        iframe = document.createElement('iframe');
        iframe.id = hiddenIFrameID;
        iframe.style.display = 'none';
        document.body.appendChild(iframe);
    }
    iframe.src = url;
};

然后在任何你想要的地方调用这个函数:

downloadURL(“path / to /我的文件”);

我建议您使用mousedown事件,它被称为BEFORE the click事件。这样,浏览器就可以自然地处理点击事件,从而避免了任何奇怪的代码:

(function ($) {


    // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
    $(document).ready(function () {

        var url = '/private/downloads/myfile123.pdf';
        $("a#someID").on('mousedown', function () {
            $(this).attr("href", url);
        });

    });
})(jQuery);