4
I have an Angular 5 application that requests 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 you create a route that is accessible without credentials, through the browser I can download, but through the API returns me some strange characters.
My API request (Angula 5):
Angular function
download(e) {
e.preventDefault();
this.httpService.builder('/registrations/download').download()
.then((res) => {
let blob = new Blob([res], { type: 'text/csv' });
let url= window.URL.createObjectURL(blob);
window.open(url);
});
}
Angular service:
download() {
let header: Headers;
let token = this.getCookie('token');
this.header = new Headers({'Authorization': 'Bearer ' + token, 'Accept': 'application/csv', 'responseType': 'blob'});
let observable = this.watch(this.http.get(this.url, {headers: this.header}));
return this.toPromise(observable);
}
Lumen 5.6
public function downloadExcel(){
$data = $this->model->all();
$headers = [
'Access-Control-Allow-Origin' => '*',
'Accept' => 'application/csv',
'responseType' => 'blob'
];
$teste = Excel::create('Laravel Excel', function($excel)use($data) {
$excel->sheet('Excel sheet', function($sheet) use ($data) {
$header = array(
'ID',
'First Name',
'Last Name',
);
$sheet->fromArray(array($header), null, 'A1', false, false);
foreach ($data as $row){
$row = $row->toArray();
$sheet->fromArray(array($row), null, 'A1', false, false);
}
});
})->download('xls', $headers);
return response()->download($teste, 'myfile.csv', [
'Content-Type' => 'text/csv',
'Content-Disposition' => "attachment; filename='myfile.csv'",
]);
}
Please enter the Maatwebsite Excel version
– Jorge Costa
2.1, but the library is working correctly, it creates the file, because if I create a direct route through the browser I can create and download the xls file.
– Laranja Mecânica