Tenho uma aplicação Angular 5 que faz uma requisição ao backend feito em Lumen 5.6, neste backend, tenho uma função que cria um ficheiro excel, com a biblioteca Maatwebsite\Excel, para download. No entanto não estou a conseguir fazer download do ficheiro através da API, caso crie uma rota que seja acessivel sem credenciais, através do browser consigo fazer download, mas pela API retorna-me uns caracteres esquisitos.
O que me retorna neste momento:
A minha requisição da API (Angula 5):
Função do angular
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);
});
}
Service do angular:
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'",
]);
}