Search code examples
phpexcelangularlaravel-5maatwebsite-excel

Angular2: Download xls file I've got from back-end


I'm using Laravel 5.1 REST API and maatwebsite solution in order to generate an Excel file on back-end. The only thing I want - is to start downloading the file on button click. Currently I'm sending an AJAX request via native Angular2 Http service and getting something like this

`��ࡱ�;��  ��������������������������������` ...

As I understand it actually returns a file, but I have to decode it in a proper way?

Is there working solution?


Solution

  • In your service or in your component from where you are sending http request. map your response to blob. Import ResponseContentType from @angular/http. For Downloading do like this:

    var link=document.createElement('a');
    link.href=window.URL.createObjectURL(res);
    link.download="District.xls";
    link.click();
    

    In service do like this:

    import { Response, ResponseContentType } from '@angular/http';
    
    downloadExcel(){
          let url = 'your url/api'
          return this.http.get(url,{headers:'pass your header',responseType: ResponseContentType.Blob})
          .map(response=>response.blob())
          .catch(error=>{return Observable.throw(error)})
      }