Bin*_*kar 5 excel file download angular
我使用角4作为前端,而内腔5.4作为后端.
我的要求是将一些数据导出为excel和zip文件.
使用{ saveAs }从'file-saver/FileSaver';包导入文件下载.
Angular 4代码:
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);
}
}
Run Code Online (Sandbox Code Playgroud)
流明代码
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);
}
Run Code Online (Sandbox Code Playgroud)
问题
const contentDispositionHeader: string = response.headers.get('Content-Disposition'); 似乎总是空的. 请帮我解决这个问题.或指定任何其他工作代码//包的角度
试试这个:
downloadExcel() {
const type = 'application/vnd.ms-excel';
const filename = 'file.xls';
const options = new RequestOptions({
responseType: ResponseContentType.Blob,
headers: new Headers({ 'Accept': type })
});
this.http.get('http://10.2.2.109/Download/exportExcel', options)
.catch(errorResponse => Observable.throw(errorResponse.json()))
.map((response) => {
if (response instanceof Response) {
return response.blob();
}
return response;
})
.subscribe(data => saveAs(data, filename),
error => console.log(error)); // implement your error handling here
}
Run Code Online (Sandbox Code Playgroud)
关键点responseType: ResponseContentType.Blob在RequestOptions和response.blob()获取响应时.
在一般情况下,不建议访问_body这样的响应特性:response._body,而是你应该调用相关的方法基于其类型来获取身体的内容(如response.blob(),response.json()等)
| 归档时间: |
|
| 查看次数: |
10003 次 |
| 最近记录: |