Download file through Typescript / Javascript

Download file through Typescript / Javascript

When working with JWT a few things get a little bit trickier. One of the examples is downloading a file through an API.

When working with sessions, you can just open a link in a new tab and as long as it's on the same domain you can check the session on the new tab and just return the file. But you can't send a JWT through a link.

Therefore you have to get a blob from the API, transform that into a file and send it to the browser. For newer browsers you can just call msSaveBlob with the blob, but on older ones like IE you have to work with a little trick.

public downloadBlob(fileName: string, blob: Blob): void {
  if (window.navigator.msSaveOrOpenBlob) {
    window.navigator.msSaveBlob(blob, fileName);
  } else {
    const anchor = window.document.createElement('a');
    anchor.href = window.URL.createObjectURL(blob);
    anchor.download = fileName;
    document.body.appendChild(anchor);
    anchor.click();
    document.body.removeChild(anchor);
    window.URL.revokeObjectURL(anchor.href);
  }
}

Basically creating an anchor element as a DOM element, running a click on it and removing it afterwards.