【问题标题】:Download file using URL in firefox not working in angular JS [duplicate]使用 Firefox 中的 URL 下载文件在 Angular JS 中不起作用 [重复]
【发布时间】:2018-07-16 11:15:45
【问题描述】:

我的代码在提供下载的谷歌浏览器中工作,在 Firefox 中它总是显示在新标签或 selftab 中,如在 Firefox 中打开的 XML 文件我应该如何下载它? 所以请给我一些建议来下载 Angular JS 或 Firefox 的 Java 脚本中的功能! 这是我尝试过的代码

var link = document.createElement('a');
link.setAttribute('href', url);
link.setAttribute('download', filename);

【问题讨论】:

  • url 指向您当前页面的哪个位置?
  • URL指向s3-server获取文件
  • 你知道巴拉吉·达莫代尔吗?他比你早一小时问了同样的问题。 stackoverflow.com/questions/48641375/…
  • 不,我不知道,但我要工作 2 天才能找到解决方案,但我没有找到任何解决方案
  • 一种可能的解决方法,取决于您的 s3 配置:fetch(url).then(r=>r.blob()).then(b=>{let a=document.createElement('a'); a.href=URL.createObjectURL(b);a.download=filename;document.body.appendChild(a);a.click();document.body.removeChild(a);

标签: javascript jquery angularjs


【解决方案1】:

您正在创建的锚标记也需要添加到 Firefox 中的 DOM,以便在 click 事件中被识别。

document.body.appendChild(link);
link.click();

【讨论】:

  • 感谢您的回答,但它直接在 Firefox 中打开文本文件,在 chrome 中它工作正常
【解决方案2】:

问题是,您必须使用 javascript 函数 encodeURIComponent(URI) 对 url 进行编码,并且就像 Catalin lancu 在我之前所说的那样,将锚标记添加到 DOM。

这是我之前写的一个用于下载文件的函数:

function downloadFile(content, filename, type){
  var a = document.createElement('a');
  a.href = type+','+encodeURIComponent(content);
  a.target = '_blank';
  a.download = filename;
  document.body.append(a);
  a.click();
  document.body.removeChild(a);
}

希望这会有所帮助。

【讨论】:

  • 感谢您的回复,但我没有文件内容,在我的回复中我只得到 file-Url 和文件名,所以我不能使用它
猜你喜欢
  • 1970-01-01
  • 2018-09-13
  • 1970-01-01
  • 1970-01-01
  • 2019-01-28
  • 2015-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多