有什么方法可以模仿锚标签的下载属性? [英] Any way to mimic the download attribute of an anchor tag?

查看:66
本文介绍了有什么方法可以模仿锚标签的下载属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

<a>标记的download属性有助于Edge

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(与ASP.NET MVC控制器对话):

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

推荐答案

我不知道有任何Javascript函数或设置可让您在下载时更改文件名,或任何模仿<a>上的download属性的函数标签.

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.

在类似的问题中, user3758133的答案概述了一种可替代方法,您可以通过编程方式创建链接,并附上正确的download属性并触发点击:

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();
});

这篇关于有什么方法可以模仿锚标签的下载属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆