Any way to mimic the download attribute of an anchor tag?

流过昼夜 提交于 2019-12-12 17:21:25

问题


The download attribute of an <a> tag helps Edge open download links more nicely (i.e. it closes the target tab once it realises it won't be used). Is there any way to do that when Javascript is responsible for initiating the download? As in

HTML:

<span class='btn-link' onclick='openReport(@orderNumber, @tableBodyId); return false;'>

Javascript (talking to ASP.NET MVC controller):

function openReport(orderNumber, tableBodyId) {
    var url = "/Reports/ValuationReportDocPdf?orderNumber=" + orderNumber;
    var win = window.open(url, '');
    setTimeout(function () { location.reload(); }, 3000);
}

回答1:


I'm not aware of any Javascript function or setting that lets you change the filename when downloading, or any that imitates the download attribute on <a> tags.

In a similar question, this answer by user3758133 outlines a workaround where you programmatically create a link, attach the proper download attribute and trigger a click:

("#downloadbutton").click(function() {
  //var content = content of file;
  var dl = document.createElement('a');
  dl.setAttribute('href', 'data:text/csv;charset=utf-8,' + encodeURIComponent(content));
  dl.setAttribute('download', 'filename.txt');
  dl.click();
});


来源:https://stackoverflow.com/questions/42468049/any-way-to-mimic-the-download-attribute-of-an-anchor-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!