0
votes

I was trying to download .xls file from server but it's throwing error like in below:->

error is:

SyntaxError: Unexpected token � in JSON at position 0 at JSON.parse () at XMLHttpRequest.onLoad (http://localhost:4200/vendor.js:31219:51) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2761:31) at Object.onInvokeTask (http://localhost:4200/vendor.js:72221:33) at ZoneDelegate.push../node_modules/zone.js/dist/zone.js.ZoneDelegate.invokeTask (http://localhost:4200/polyfills.js:2760:36) at Zone.push../node_modules/zone.js/dist/zone.js.Zone.runTask (http://localhost:4200/polyfills.js:2528:47) at ZoneTask.push../node_modules/zone.js/dist/zone.js.ZoneTask.invokeTask [as invoke] (http://localhost:4200/polyfills.js:2836:34) at invokeTask (http://localhost:4200/polyfills.js:3880:14) at XMLHttpRequest.globalZoneAwareCallback (http://localhost:4200/polyfills.js:3906:17) text: "��ࡱ�;�� "

In my component, i implemented function which call service and i am using file saver to save a file, but its throwing error.

download.component.ts:->

import * as FileSaver from 'file-saver';
     export_licence(){
        this.service.export_licence().subscribe((file: Blob) => {
          FileSaver.saveAs(file,'degreeCertificate.xls');
        }, (err) => {
          console.log("Download Error:", err);
        });
      }

download.service.ts :->

export_licence() {
  return this.http.post(this.export_licence_url,{responseType: "blob"});
}

I should be able to download .xls file from server, any help will be appreciated.

2

2 Answers

0
votes

Check the response Header set properly (For content type) and also ensure the file is not corrupted.

Seems Duplicate downloading xlsx file in angular 2 with blob

0
votes

this worked for me

download.component.ts:->

import * as FileSaver from 'file-saver';
     export_licence(){
        this.service.export_licence().subscribe((file: Blob) => {
          FileSaver.saveAs(file,'degreeCertificate.xls');
        }, (err) => {
          console.log("Download Error:", err);
        });
      }

in service i added header properly.

download.service.ts:->

export_licence() {
  let headers = new Headers({ 
    'Content-Type':'application/json', 
    'Accept': 'application/.xls'
 });
 let options = { headers : headers };
  return this.http.post(this.export_licence_url,options,{responseType: "blob"});
}