简体   繁体   中英

Angular 4file download (Internet Explorer 11)

Sorry if there is another post talking about this, but I can't find it and it's driving me crazy.

I made a webservice that returns a file in form of a byte array, and it works fine. After that,

On the other side, I'm developing an Angular 4 site that calls de webservice mentioned and try to download the obtained file. So I came up with the following code:

downloadFile() {
  let theFile;
  this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
    .subscribe(data => {
      theFile = new Blob([data], { type: 'application/octet-stream' });
      let url = window.URL.createObjectURL(theFile);
      console.log(url);
      const link = document.createElement('a');
      link.href = url;
      link.download = 'file.pdf';
      console.log(link);
      link.click();
    },
    error => {
      console.log(error);
    },
    () => console.log('File download completed.'));
}

This code works as expected using Chrome, but Internet Explorer doesn't download the file to the browser.

Thanks to console.log() I can see that the link element created is different:

Could anybody help me? Thanks a lot in advance!!

I had to implement same feature for my app and I used this library: File-Saver

It has come quiet handy.

Finally, I found this similar post . I modified my function and now look like this (it works perfectly now both in Chrome and IE11):

downloadFile() {
  let theFile;
  this.http.get(FILE_DOWNLOAD_ENDPOINT, { responseType: 'blob' })
    .subscribe(data => {
      theFile = new Blob([data], { type: 'application/octet-stream' });
      if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(theFile, 'file.pdf');
      } else {
        const url = window.URL.createObjectURL(theFile);
        window.open(url);
        const link = document.createElement('a');
        link.href = url;
        link.download = 'file.pdf';
        link.click();
      }
    },
    error => {
      console.log(error);
    },
    () => console.log('File download completed.'));
}

Thank you!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM