我有一个Angular 7前端,我正在尝试从Laravel 5.8 API下载PDF文件。不幸的是,它不起作用。通常可以这样做吗?
代码如下:
download(document) {
this.apiService.downloadDocument(document).subscribe((document) => {
this.notification.success('Download started.');
},error1 => console.log(error1));
}
现在我尝试了两种选择:
选项1:无标题
downloadDocument(document): Observable<any> {
return this.httpClient.post<any>(`${this.PHP_API_SERVER}/downloadDocument`,document)
}
选项2:带标题
downloadDocument(document): Observable<any> {
let headers = new HttpHeaders();
headers = headers.set('accept','application/pdf');
return this.httpClient.post<any>(`${this.PHP_API_SERVER}/downloadDocument`,document,{headers: headers})
}
现在是后端部分:
public function downloadDocument(Request $request)
{
try {
return Storage::download($request->name_hash); // name_hash is the path to the file
} catch (QueryException $e) {
return response()->json($e,Response::HTTP_INTERNAL_SERVER_ERROR);
}
}
有趣的是,它似乎起作用了,因为我在预览中的开发人员工具的“网络”选项卡中看到了PDF,(我猜是解码了吗?)PDF。 看起来像这样:
%PDF-1.4
%äüöÃ
2 0 obj
<</Length 3 0 R/Filter/flateDecode>>
stream
xU˪ãFÝû+z°§«ú
[...]
但是下载没有开始! 上面我的代码中“ error1”中的console.log只是说:
OK
我不知道这是否太多,但是这里还有请求和响应头。
响应标题:
access-control-allow-headers: Content-Type,accept,Authorization,X-Requested-With,Application
access-control-allow-methods: POST,GET,OPTIONS,PUT,DELETE
access-control-allow-origin: *
cache-control: private,must-revalidate
content-disposition: attachment; filename=rD1579koch77OUIfnPZmnJaIgDUnUMSINaYGdKO8.pdf
content-length: 212677
content-type: application/pdf
date: Sun,10 Nov 2019 19:37:14 GMT
expires: -1
pragma: no-cache
server: nginx
status: 200
vary: Authorization
x-ratelimit-limit: 60
x-ratelimit-remaining: 59
请求标头:
:authority: api.myapi.de
:method: POST
:path: /api/downloadDocument
:scheme: https
accept: application/json,text/plain,*/*
accept-encoding: gzip,deflate,br
accept-language: de-DE,de;q=0.9,en-US;q=0.8,en;q=0.7,nl;q=0.6
authorization: Bearer [my-token-is-here]
content-length: 224
content-type: application/json
origin: http://localhost:4200
referer: http://localhost:4200/
sec-fetch-mode: cors
sec-fetch-site: cross-site
user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_1) AppleWebKit/537.36 (KHTML,like Gecko) Chrome/78.0.3904.70 Safari/537.36