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

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

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

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


当前回答

Firefox和Chrome测试:

var link = document.createElement('a');
link.download = 'fileName.ext'
link.href = 'http://down.serv/file.ext';

// Because firefox not executing the .click() well
// We need to create mouse event initialization.
var clickEvent = document.createEvent("MouseEvent");
clickEvent.initEvent("click", true, true);

link.dispatchEvent(clickEvent);

这实际上是firefox的“chrome”方式解决方案(我没有在其他浏览器上测试过,所以请留下关于可编译性的评论)

其他回答

这些函数在stacktrace.js中使用:

/**
 * Try XHR methods in order and store XHR factory.
 *
 * @return <Function> XHR function or equivalent
 */
var createXMLHTTPObject = function() {
    var xmlhttp, XMLHttpFactories = [
        function() {
            return new XMLHttpRequest();
        }, function() {
            return new ActiveXObject('Msxml2.XMLHTTP');
        }, function() {
            return new ActiveXObject('Msxml3.XMLHTTP');
        }, function() {
            return new ActiveXObject('Microsoft.XMLHTTP');
        }
    ];
    for (var i = 0; i < XMLHttpFactories.length; i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
            // Use memoization to cache the factory
            createXMLHTTPObject = XMLHttpFactories[i];
            return xmlhttp;
        } catch (e) {
        }
    }
}

/**
 * @return the text from a given URL
 */
function ajax(url) {
    var req = createXMLHTTPObject();
    if (req) {
        try {
            req.open('GET', url, false);
            req.send(null);
            return req.responseText;
        } catch (e) {
        }
    }
    return '';
}

仅仅7年之后,这里出现了一行jQuery解决方案,使用表单而不是iframe或链接:

$('<form></form>')
     .attr('action', filePath)
     .appendTo('body').submit().remove();

我已经测试过了

Chrome 55 Firefox 50 边缘IE8-10 iOS 10 (Safari/Chrome) Android浏览器

如果有人知道这个解决方案的任何缺点,我很乐意听听。


完整的演示:

<html>
<head><script src="https://code.jquery.com/jquery-1.11.3.js"></script></head>
<body>
<script>
    var filePath = window.prompt("Enter a file URL","http://jqueryui.com/resources/download/jquery-ui-1.12.1.zip");
    $('<form></form>').attr('action', filePath).appendTo('body').submit().remove();
</script>
</body>
</html>

你必须从服务器和客户端(web应用程序)两方面进行操作。

在服务器上,设置名为Content-Disposition https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Disposition的报头

// nodejs express
  res.set('Content-Disposition', `attachment; filename="${self.creationName}"`)

使用上面的头文件,服务器会告诉浏览器响应是一个文件,它应该下载并以给定的名称保存,否则浏览器可能会将文件保存为“attachments (1).zip”之类的文件

接下来,我们查看客户端,创建一个锚链接并自动单击它。

function downloadThroughAnchorLink(downloadUrl: string, fileName: string) {
    const a = document.createElement('a')
    a.href = downloadUrl;
    // We provided a header called Content-Disposition so we dont need to set "a.download" here
    // a.download = fileName || 'download'
    a.click()
}

这样就行了。

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

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

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

来自Corbacho的优秀解决方案,我只是适应了摆脱var

function downloadURL(url) {
    if( $('#idown').length ){
        $('#idown').attr('src',url);
    }else{
        $('<iframe>', { id:'idown', src:url }).hide().appendTo('body');
    }
}