Download File via API + Lumen + Maatwebsite \ Excel

4

I have an Angular application 5 that makes a request to the backend made in Lumen 5.6, in this backend, I have a function that creates an excel file, with the Maatwebsite \ Excel library, for download. However I am not able to download the file through the API, if I create a route that is accessible without credentials, through the browser I can download, but the API returns me some weird characters.

What brings me back this time:

MyAPIrequest(Angula5):

Anglefunction

download(e){e.preventDefault();this.httpService.builder('/registrations/download').download().then((res)=>{letblob=newBlob([res],{type:'text/csv'});leturl=window.URL.createObjectURL(blob);window.open(url);});}

Angularservice:

download(){letheader:Headers;lettoken=this.getCookie('token');this.header=newHeaders({'Authorization':'Bearer'+token,'Accept':'application/csv','responseType':'blob'});letobservable=this.watch(this.http.get(this.url,{headers:this.header}));returnthis.toPromise(observable);}

Lumen5.6

publicfunctiondownloadExcel(){$data=$this->model->all();$headers=['Access-Control-Allow-Origin'=>'*','Accept'=>'application/csv','responseType'=>'blob'];$teste=Excel::create('LaravelExcel',function($excel)use($data){$excel->sheet('Excelsheet',function($sheet)use($data){$header=array('ID','FirstName','LastName',);$sheet->fromArray(array($header),null,'A1',false,false);foreach($dataas$row){$row=$row->toArray();$sheet->fromArray(array($row),null,'A1',false,false);}});})->download('xls',$headers);returnresponse()->download($teste,'myfile.csv',['Content-Type'=>'text/csv','Content-Disposition'=>"attachment; filename='myfile.csv'",
    ]);
}
    
asked by anonymous 13.07.2018 / 12:03

1 answer

0

The problem is in the first parameter of the download method.

->download('xls', $headers);

You are telling the library to generate a xls , while in the rest of the code you are using CSV.

You can change xls to csv which will bring a csv file to you. You can also remove the last 4 lines of your action.

 return response()->download($teste, 'myfile.csv', [
    'Content-Type' => 'text/csv',
    'Content-Disposition' => "attachment; filename='myfile.csv'",
]);

The library already sets these values when you call the download method as you can see looking at the code.

    
16.07.2018 / 20:21