【问题标题】:Unable to serve a file to download in IE from Angular无法从 Angular 提供要在 IE 中下载的文件
【发布时间】:2017-10-11 11:43:48
【问题描述】:

我正在尝试为我的用户生成一个文本文件,下面的代码在除 IE 和 Edge 之外的所有浏览器中都能很好地完成这项工作(在后者中,我无法控制文件的名称,但它至少是生成的) .

emitFile(stage: any): void {
  const blob = new Blob([stage.elaboration], { type: "text/csv" });
  const url = window.URL.createObjectURL(blob);
  const anchor = document.createElement("a");
  anchor.href = url;
  anchor.download = "ff-rocks-ie-sucks.txt";
  anchor.click();
}

在这方面有 an open issue ticket,但它的日期是 18 个月前,而且最近的活动也不是最近的。这似乎是一个希望破灭的地方。

我还没有找到任何合理的解决方法。我看到的那些要么不起作用,要么包含一个(非常明智但不可行)的建议,即为了鸭子而获得体面的浏览器。而且我认为这更像是一个错字而不是鸟类参考。

应该怎么办?

【问题讨论】:

  • IE11 不支持下载属性。使用文件时,IE 中的结果有所不同:协议。或本地主机。
  • 没有解决方法吗?我希望有可能实现以某种方式。我想我不走运...请将其作为回复发布,以便(不情愿地)接受。 :)

标签: angular file typescript internet-explorer download


【解决方案1】:

您应该尝试使用 msSaveBlob() 而不是下载属性。

emitFile(stage: any): void {
  const blob = new Blob([stage.elaboration], { type: "text/csv" });
  window.navigator.msSaveBlob(blob,"ff-rocks-ie-sucks.txt");
}

它应该适用于 IE 和 Edge。

编辑: IE、FF 和 Chrome 的完整解决方案是这样的:

emitFile(stage: any): void {
  const blob = new Blob([stage.elaboration], { type: "text/csv" });
  if(window.navigator.msSaveOrOpenBlob) //IE & Edge
  {
    //msSaveBlob only available for IE & Edge
    window.navigator.msSaveBlob(blob,"ff-rocks-ie-sucks.txt");
  }
  else //Chrome & FF
  {
    const url = window.URL.createObjectURL(blob);
    const anchor = document.createElement("a");
    anchor.href = url;
    anchor.download = "ff-rocks-ie-sucks.txt";
    document.body.appendChild(anchor); //For FF
    anchor.click();
    //It's better to remove the elem
    document.body.removeChild(anchor);
  }
}

【讨论】:

  • 您是否建议emitFile 方法应该识别应用程序在哪个浏览器中运行并做出相应反应?或者有没有办法根据某些标记调用它的正确版本?
  • 否,由于 msSaveBlob 功能,此解决方案仅适用于 IE 和 Edge。您需要为 FF 和 Chrome 添加条件:if(window.navigator.msSaveOrOpenBlob) //IE & Edge { }else{//Chrome & FF}
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-01
  • 2017-08-26
  • 2011-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多