无法在Angular中提供从IE下载的文件

Don*_*ana 0 internet-explorer file download typescript angular

我正在尝试为我的用户生成一个文本文件,下面的代码在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();
}
Run Code Online (Sandbox Code Playgroud)

在这方面有一张公开的发行票,但它的日期是18个月前,最近的活动相当不紧急.似乎这是一个希望夭折的地方.

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

该怎么办呢?

小智 7

您应该尝试使用msSaveBlob()而不是download属性.

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

它应该适用于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);
  }
}
Run Code Online (Sandbox Code Playgroud)