在不离开页面的情况下打开下载窗口的最简单方法

mko*_*yak 104 javascript

什么是最好的跨浏览器方式来打开下载对话框(假设我们可以设置内容处置:标题中的附件)而无需导航离开当前页面,或打开弹出窗口,这在IE6中无法正常工作.

moz*_*ras 188

这个javascript很好,它不会打开一个新窗口或选项卡.

window.location.assign(url);
Run Code Online (Sandbox Code Playgroud)

  • 这与window.location = url相同; "每当为位置对象分配新值时,将使用URL加载文档,就像使用修改后的URL调用window.location.assign()" - https://developer.mozilla.org/en-美国/文档/网络/ API/window.location的 (16认同)
  • 这会导致WebSocket连接断开连接. (13认同)
  • 我使用了相同的解决方案,但它在同一个选项卡中打开文件,而不是打开下载对话框. (4认同)
  • 当使用IE11时,我发现这导致JS停止.因此,对于IE 11,我使用了window.open(url,'_ blank'),它确实打开了另一个选项卡,但是当它解决文件时该选项卡是关闭的.这使JS保持运行. (3认同)
  • 如果url用于下载页面,则与window.open(url,'_ self')相同. (2认同)

0x0*_*00f 90

7年过去了,好的.我不知道它是否适用于IE6,但这会在FF和Chrome中提示OpenFileDialog.

var file_path = 'host/path/file.ext';
var a = document.createElement('A');
a.href = file_path;
a.download = file_path.substr(file_path.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Run Code Online (Sandbox Code Playgroud)

  • 这不再起作用了https://developers.google.com/web/updates/2018/02/chrome-65-deprecations (10认同)
  • @Manoj Rana-我检查了FF 58.0.2(64位)是否正常工作。如果删除两行_document.body.appendChild(a); _ _document.body.removeChild(a); _ (2认同)
  • @ user1933131 chrome仅针对跨域删除 (2认同)
  • @PauliusDragunas 它仍然有效。但它不适用于跨域 url。 (2认同)

jao*_*jao 23

我总是在下载链接中添加一个target ="_ blank".这将打开一个新窗口,但只要用户单击"保存",新窗口就会关闭.

  • 这是最好的答案.在Internet Explorer中,将"target ="_ blank"'添加到要下载的链接将阻止浏览器导航(打印"HTML1300:Navigation occurred"),从而使页面处于不一致状态. (2认同)

Geo*_*orn 19

将其放在HTML头部分中,将urlvar 设置为要下载的文件的URL:

<script type="text/javascript">  
function startDownload()  
{  
     var url='http://server/folder/file.ext';    
     window.open(url, 'Download');  
}  
</script>
Run Code Online (Sandbox Code Playgroud)

然后把它放在体内,这将在5秒后自动开始下载:

<script type="text/javascript">  
setTimeout('startDownload()', 5000); //starts download after 5 seconds  
</script> 
Run Code Online (Sandbox Code Playgroud)

(从这里开始.)

  • 这不起作用,因为在IE6中,如果用户点击"保存",文件将被保存,但弹出窗口保持打开状态.这是不可接受的. (2认同)

alo*_*d05 15

正如这个问题所暗示的那样,我一直在寻找一种使用javascript来启动文件下载的好方法.然而,这些答案没有帮助.然后我做了一些xbrowser测试,发现iframe在IE> 8的所有现代浏览器上效果最好.

downloadUrl = "http://example.com/download/file.zip";
var downloadFrame = document.createElement("iframe"); 
downloadFrame.setAttribute('src',downloadUrl);
downloadFrame.setAttribute('class',"screenReaderText"); 
document.body.appendChild(downloadFrame); 
Run Code Online (Sandbox Code Playgroud)

class="screenReaderText" 是我的类来设置存在但不可见的内容.

CSS:

.screenReaderText { 
  border: 0; 
  clip: rect(0 0 0 0); 
  height: 1px; 
  margin: -1px; 
  overflow: hidden; 
  padding: 0; 
  position: absolute; 
  width: 1px; 
}
Run Code Online (Sandbox Code Playgroud)

与html5boilerplate中的.visuallyHidden相同

我更喜欢这个javascript window.open方法,因为如果链接被破坏,iframe方法根本不做任何事情,而不是重定向到空白页面说文件无法打开.

window.open(downloadUrl, 'download_window', 'toolbar=0,location=no,directories=0,status=0,scrollbars=0,resizeable=0,width=1,height=1,top=0,left=0');
window.focus();
Run Code Online (Sandbox Code Playgroud)


cнŝ*_*ŝdk 8

我知道问题已被问到,7 years and 9 months ago但许多发布的解决方案似乎不起作用,例如<iframe>仅使用作品FireFox但不能使用Chrome.

最佳方案:

打开文件下载弹出窗口的最佳工作解决方案JavaScript是使用HTML链接元素,而无需将链接元素附加到document.body其他答案中所述的链接元素.

您可以使用以下功能:

function downloadFile(filePath){
    var link=document.createElement('a');
    link.href = filePath;
    link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
    link.click();
}
Run Code Online (Sandbox Code Playgroud)

在我的应用程序中,我这样使用它:

downloadFile('report/xls/myCustomReport.xlsx');
Run Code Online (Sandbox Code Playgroud)

工作演示:

function downloadFile(filePath) {
  var link = document.createElement('a');
  link.href = filePath;
  link.download = filePath.substr(filePath.lastIndexOf('/') + 1);
  link.click();
}

downloadFile("http://www.adobe.com/content/dam/Adobe/en/accessibility/pdfs/accessing-pdf-sr.pdf");
Run Code Online (Sandbox Code Playgroud)

注意:

  • 您必须使用该link.download属性,以便浏览器不会在新选项卡中打开该文件并触发下载弹出窗口.
  • 这是使用多种文件类型(docx,xl​​sx,png,pdf,...)测试的.

  • 这个解决方案适用于我的 Chrome、Safari 和 Firefox :) (2认同)

lor*_*isi 7

使用 HTML5 Blob对象-URL 文件 API:

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see /sf/ask/3499174171/
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile
Run Code Online (Sandbox Code Playgroud)

/**
 * Save a text as file using HTML <a> temporary element and Blob
 * @see https://stackoverflow.com/questions/49988202/macos-webview-download-a-html5-blob-file
 * @param fileName String
 * @param fileContents String JSON String
 * @author Loreto Parisi
*/
var saveBlobAsFile = function(fileName,fileContents) {
    if(typeof(Blob)!='undefined') { // using Blob
        var textFileAsBlob = new Blob([fileContents], { type: 'text/plain' });
        var downloadLink = document.createElement("a");
        downloadLink.download = fileName;
        if (window.webkitURL != null) {
            downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
        }
        else {
            downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
            downloadLink.onclick = document.body.removeChild(event.target);
            downloadLink.style.display = "none";
            document.body.appendChild(downloadLink);
        }
        downloadLink.click();
    } else {
        var pp = document.createElement('a');
        pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
        pp.setAttribute('download', fileName);
        pp.onclick = document.body.removeChild(event.target);
        pp.click();
    }
}//saveBlobAsFile
Run Code Online (Sandbox Code Playgroud)

  • 我觉得这是最好的方法! (2认同)

Tay*_*Mac 5

如果链接是有效的文件URL,只需指定window.location.href即可.

但是,有时链接无效,并且需要iFrame.

执行正常的event.preventDefault以防止窗口打开,如果您使用的是jQuery,这将起作用:

$('<iframe>').attr('src', downloadThing.attr('href')).appendTo('body').on("load", function() {
   $(this).remove();
});
Run Code Online (Sandbox Code Playgroud)


Bnr*_*rdo 5

修改窗口的位置可能会引起一些问题,尤其是当您拥有像websocket这样的持久连接时。因此,我总是采用良好的旧iframe解决方案。

的HTML

<input type="button" onclick="downloadButtonClicked()" value="Download"/>
...
...
...
<iframe style="display:none;" name="hiddenIframe" id="hiddenIframe"></iframe>
Run Code Online (Sandbox Code Playgroud)

Java脚本

function downloadButtonClicked() {
    // Simulate a link click
    var url = 'your_download_url_here';
    var elem = document.createElement('a');
    elem.href = url;
    elem.target = 'hiddenIframe';
    elem.click();
}
Run Code Online (Sandbox Code Playgroud)


Gau*_*nal 5

根据新的 chrome 规范的最佳解决方案https://developers.google.com/web/updates/2018/02/chrome-65-deprecations

普通 JavaScript

public static downloadFile(url: string): void {
     const xmlHttp = new XMLHttpRequest();
     xmlHttp.onreadystatechange = () => {
       if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
         const blobUrl = window.URL.createObjectURL(xmlHttp.response);
         const e = document.createElement('a');
         e.href = blobUrl;
         e.download = blobUrl.substr(blobUrl.lastIndexOf('/') + 1);
         document.body.appendChild(e);
         e.click();
         document.body.removeChild(e);
       }
     };
     xmlHttp.responseType = 'blob';
     xmlHttp.open('GET', url, true);
     xmlHttp.send(null);
   }
Run Code Online (Sandbox Code Playgroud)

如果您使用的是角度尝试这个。

async downloadBrochure(url: string) {
    try {
      const res = await this.httpClient.get(url, { responseType: 'blob' }).toPromise();
      this.downloadFile(res);
    } catch (e) {
      console.log(e.body.message);
    }
  }

  downloadFile(data) {
    const url = window.URL.createObjectURL(data);
    const e = document.createElement('a');
    e.href = url;
    e.download = url.substr(url.lastIndexOf('/') + 1);
    document.body.appendChild(e);
    e.click();
    document.body.removeChild(e);
  }
Run Code Online (Sandbox Code Playgroud)