无需离开页面即可打开下载窗口的最简单方法(windows.open download file)

什么是最好的跨浏览器的方式来打开一个下载对话框(让我们假设我们可以设置 content-disposion:附件中的标题),而无需导航离开当前页面,或打开弹出窗口,这在 Internet Explorer 中不能很好地工作(IE)6。

什么是最好的跨浏览器的方式来打开一个下载对话框(让我们假设我们可以设置 content-disposion:附件中的标题),而无需导航离开当前页面,或打开弹出窗口,这在 Internet Explorer 中不能很好地工作(IE)6。

232

这个 javascript 很好,它不会打开一个新窗口或标签。

window.location.assign(url);
136

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);
42

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

最佳解决方案:

JavaScript中打开文件下载弹出窗口的最佳working solution是使用HTML链接元素,无需将链接元素附加到document.body,如其他答案所述。

您可以使用以下函数:

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

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

downloadFile('report/xls/myCustomReport.xlsx');

工作演示:

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");
Note:

您必须使用link.download属性,以便浏览器不会在新选项卡中打开文件并触发下载弹出窗口。

这是用几种文件类型(docx,xlsx,png,pdf,...)测试的。

29

我总是在下载链接中添加一个 target =“_blank”,这将打开一个新窗口,但是一旦用户单击保存,新窗口就会关闭。

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(57)
FileMakerPro和Onedrive
上一篇
如何在Windows或Linux上安装 dns-sd命令行测试工具
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(22条)