我在使用来自 UserFrosting API 的 Angular 2+ 的 HttpClient get() 方法接收 Excel 文件的 Blob 时遇到问题。
这是 Userfrosting API 的代码:
public function apiGetAPExport(Request $request, Response $response, $args)
{
$objPHPExcel = $this->getAPExcelObject($apfilename); // create the PHPExcel Object.
// Redirect output to a client's web browser (Excel5)
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment;filename="'.$apfilename.'.xls"');
header('Content-Transfer-Encoding: binary');
header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
header ('Pragma: public'); // HTTP/1.0
header('Access-Control-Allow-Origin: *');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
exit;
}
我正在使用 PHP Excel 生成 Excel 文件。
这是角函数:
btn_createAPfile(){
const url = this.AppService.fetchHost()+'/api/ap-export';
let req = this.http.get(url, {responseType: 'blob'})
.pipe(
map( // Log the result or error
data => {
console.log(data);
let blob = new Blob([data], { type: "application/vnd.ms-excel"});
return blob;
},
error => console.error("err: ", error)
)
);
req.subscribe(blob => {
console.log("dbg: ", blob);
let link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "apfile.xls";
link.click();
this.populateInvoices();
setTimeout(function () {
window.URL.revokeObjectURL(url);
}, 0);
});
}
我在这里要做的是使用 http.get() 下载 Excel 文件,下载完成后,使用populateInvoices()
. 但问题是,当我尝试触发 Angular 函数时,我的浏览器控制台上总是会出现此错误:
GET http://192.168.33.10/api/ap-export 500 (Internal Server Error)
Access to XMLHttpRequest at 'http://192.168.33.10/api/ap-export' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Uncaught HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: null, ok: false, …}
我尝试直接将 URL 输入到浏览器的地址栏,它工作正常。
我知道我可以下载,windows.open()
但我不能用它重新填充表格。
请帮助我,我在这里缺少什么?