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

Viewed 585

I am trying to download a file with JavaScript and not let it open in a new tab or 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.

This has to happen in client side 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.

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);
}
1 Answers

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).

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.

Related