I am using angular 4 as frond end and lumen 5.4 as back end.
My requirement is to export some data as excel and zip file.
Using import { saveAs }
from 'file-saver/FileSaver';
package for file download.
Angular 4 Code:
downloadExcel() {
const type = 'application/vnd.ms-excel';
const headers = { headers: new Headers({ 'Accept': type }) };
const filename = 'file.xls';
this.http.get('http://10.2.2.109/Download/exportExcel', headers)
.toPromise()
.then(response => this.saveToFileSystem(response, type, filename));
return false;
}
private saveToFileSystem(response, __type, filename) {
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
if (contentDispositionHeader !== null) {
const parts: string[] = contentDispositionHeader.split(';');
//const filename = parts[1].split('=')[1];
const blob = new Blob([response._body], { type: __type });
saveAs(blob, filename);
} else {
alert('Cant download.....');
// handling download condition if content disposition is empty
const blob = new Blob([response._body], { type: __type });
saveAs(blob, filename);
}
}
Lumen Code
public function exportExcel(Request $request) {
$file = storage_path();
$file_name = 'book1.xls';
$headers = [
'Content-type' => 'application/vnd.ms-excel',
'Content-Disposition' => 'attachment;filename="' . $file_name,
'X-Filename' => $file_name,
'Content-Transfer-Encoding' => 'binary',
'Content-Length' => filesize($file . '/' . $file_name),
'Cache-Control' => 'max-age=0',
'Cache-Control' => 'max-age=1',
'Expires' => 'Mon, 26 Jul 1997 05:00:00 GMT',
'Last-Modified' => gmdate('D, d M Y H:i:s') . ' GMT',
'Cache-Control' => 'cache, must-revalidate',
'Pragma' => 'public',
'Set-Cookie' => 'fileDownload=true; path=/',
'Access-Control-Expose-Headers' => 'Content-Length,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma'
];
return response()->download($file . '/' . $file_name, $file_name, $headers);
}
Issues
const contentDispositionHeader: string = response.headers.get('Content-Disposition');
seems always empty.- We cant open downloaded file, shows corrupted message.
- It working for text file download
Please help me to resolve this issue. OR specify any other working code//package for angular
You could use json2csv provided the input data is in JSON format. The output of the function will be CSV which can be opened in Microsoft Excel or Google Sheets.
Install the package:
Add the following to your component:
Try this:
The key points are
responseType: ResponseContentType.Blob
on the RequestOptions andresponse.blob()
when getting back the response.In general, it's not recommended to access the
_body
property of the response like this:response._body
, but instead you should call the relevant method to get the body content based on its type (likeresponse.blob()
,response.json()
, etc)