DonkeyBanana
DonkeyBanana

Reputation: 3556

Unable to serve a file to download in IE from Angular

I'm trying to produce a text file to my users and the code below does the job perfectly well in all browsers except IE and Edge (in the latter, I can't control the file's name but it's at least produced).

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

There's an open issue ticket in that regard but it's dated 18 months back and the recent activity is rather un-recent. It seems that it's a place where hopes come to die.

I haven't found any reasonable workarounds. The ones I've seen were either non-working or included a (very wise but infeasible) suggestion to get decent browsers for duck's sake. And I believe it was more of a typo than a bird reference.

What should be done about it?

Upvotes: 1

Views: 6421

Answers (1)

Romain B.
Romain B.

Reputation: 654

You should try using msSaveBlob() instead of the download attribute.

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

It should work fine for IE and Edge.

EDIT : The full solution for IE, FF and Chrome would be like that :

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

Upvotes: 12

Related Questions