从Slim v2.6.1服务下载pdf与Angular v1.5
问题描述:
我想从Slim v2.6.1开发的服务中下载带有Angular v1.5的pdf。从Slim v2.6.1服务下载pdf与Angular v1.5
下载文件后,我打开它,但它没有内容,页面是空白的。 我不知道为什么源文件大小是87 KB,下载的文件是135 KB。
搭配修身框架开发的服务代码是:
$app->get('/pdfReport', function() use ($app) {
try {
$path = "./Service/reports/report_test.pdf";
$app->response->setStatus(200);
$app->response()->header('Content-Type','application/pdf');
$app->response()->header('Content-Transfer-Encoding', 'Binary');
$app->response()->header('Content-disposition', 'attachment; filename="report_test"');
$app->response()->header('Content-Length', filesize($path));
$app->response()->header('Expires', '0');
$app->response()->header('Cache-Control', 'must-revalidate, post-check=0, pre-check=0');
$app->response()->header('Pragma', 'public');
ob_clean();
ob_start();
readfile($path);
$content = ob_get_clean();
$app->response()->body($content);
} catch (Exception $e) {
$arr = array('status' => "error", 'fault' => $e->getMessage());
}
});
在角代码:
vm.generateReport = function() {
var uri = "api/pdfReport";
$http.get(uri, header).success(function(data) {
var data = new Blob([data], { type: "application/pdf" });
saveAs(data, 'Report.pdf');
});
}
答
当下载的二进制数据,如PDF或图像,设置是非常重要的responseType:
vm.generateReport = function() {
var uri = "api/pdfReport";
var config = { responseType: 'blob' };
$http.get(uri, config).then(function(response) {
̶v̶a̶r̶ ̶d̶a̶t̶a̶ ̶=̶ ̶n̶e̶w̶ ̶B̶l̶o̶b̶(̶[̶d̶a̶t̶a̶]̶,̶ ̶{̶ ̶t̶y̶p̶e̶:̶ ̶"̶a̶p̶p̶l̶i̶c̶a̶t̶i̶o̶n̶/̶p̶d̶f̶"̶ ̶}̶)̶;̶
var data = response.data;
saveAs(data, 'Report.pdf');
});
}
欲了解更多信息,请参阅MDN Web API Reference - XHR responseType