![](/img/trans.png)
[英]In Angular 5 how can I force a download of a PDF retrieved from an authenticated API
[英]How can i download the pdf directly from the API (Angular)?
我需要從Angular中的一個API下載一個PDF。
所以,我寫了一個服務來調用 API:
getPDF(id:any) {
return this.http.get(
`url?=${id}`,
{ responseType: 'blob' as 'json', observe: 'response' }
);
}
在我的組件文件中,我正在調用服務來下載 PDF。
onGeneratepdf() {
this.service
.getPDF(
123
)
.subscribe((res: any) => {
let filename = res.header
?.get('content-disposition')
?.split(';')[1]
.split('=')[1];
let blob: Blob = res.body as Blob;
var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
});
}
點擊 GeneratePDF 后,pdf 正在下載,但問題是......它正在下載文件名undefined.pdf ...它應該以user.pdf之類的名稱下載,而且我得到的響應標頭為
access-control-allow-origin: *
cache-control: no-cache, no-store, max-age=0, must-revalidate
content-disposition: attachment; filename=user.pdf
content-type: application/pdf
請幫我解決這些問題。
提前致謝。
onGeneratepdf() {
this.service
.getPDF(
123
)
.subscribe((res: any) => {
let filename = res.headers
?.get('content-disposition')
?.split(';')[1]
.split('=')[1];
let blob: Blob = res.body as Blob;
var a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.click();
});
請嘗試上面的代碼,你寫的 res.header 應該是 res.headers
如果上面的代碼不適合你,那么看看下面的鏈接,你會在這里找到你的解決方案。
謝謝!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.