简体   繁体   English

强制从外部 url 下载文件不在新选项卡/窗口中打开

[英]Force download of file from external url not open in new tab/window

I am trying to download a file with JavaScript and not let it open in a new tab or window.我正在尝试使用 JavaScript 下载文件,而不是让它在新选项卡或 window 中打开。

What I have so far is this:我到目前为止是这样的:

var link = document.createElement("a");
link.download = filename;
link.href = fileurl;
link.click();

I've been doing a fair bit of research about this but cannot find anything that works because the file is coming from a Google Signed URL which I have no control over and cannot modify headers for.我一直在对此进行大量研究,但找不到任何可行的方法,因为该文件来自谷歌签名的 URL,我无法控制也无法修改其标题。

This has to happen in client side JavaScript/jQuery.这必须在客户端 JavaScript/jQuery 中发生。

Edit编辑

It is actually dynamic so there can be X number of files, if I could get them all to download as a zip that would be even better.它实际上是动态的,因此可以有 X 个文件,如果我可以将它们全部下载为 zip,那就更好了。

for(var i=0; i<filenames.length; i++){
    var formData = new FormData();
    formData.append('filename', filenames[i]);
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            fileurl = this.responseText;
            
            var link = document.createElement("a");
            link.download = filenames[i];
            link.href = fileurl;
            link.click();
        }
    }
    xmlhttp.open("POST", "url_to_get_download_urls");
    xmlhttp.send(formData);
}

Have you tried doing the download action in different browsers?您是否尝试过在不同的浏览器中执行下载操作? In the latest versions of Chrome, you cannot download cross-origin files (they have to be hosted on the same domain).在最新版本的 Chrome 中,您无法下载跨域文件(它们必须托管在同一域中)。

As well if the file doesn't change, have you tried hosting the file yourself and initiating the download?同样,如果文件没有更改,您是否尝试过自己托管文件并启动下载?

edit: If you're trying to bundle the items into a zip for download, that would necessitate doing the initial download on your own server and zipping there.编辑:如果您尝试将这些项目捆绑到 zip 中以供下载,则需要在您自己的服务器上进行初始下载并在那里压缩。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM