Javascript 使用正确的编码从RESTAPI下载pdf
我尝试使用以下两种方法从rest api下载pdf文件:Javascript 使用正确的编码从RESTAPI下载pdf,javascript,angular,rest,pdf,encoding,Javascript,Angular,Rest,Pdf,Encoding,我尝试使用以下两种方法从rest api下载pdf文件: download():ng.IPromise{ 返回此.http.get(this.url.getUrl()) 。然后(响应=>{ 返回新的Blob([response.data],{type:'application/pdf'}); } ) } this.service.download().then(文件=>{ var a=document.createElement(“a”), url=url.createObjectURL(文件
download():ng.IPromise{
返回此.http.get(this.url.getUrl())
。然后(响应=>{
返回新的Blob([response.data],{type:'application/pdf'});
}
)
}
this.service.download().then(文件=>{
var a=document.createElement(“a”),
url=url.createObjectURL(文件);
打开(url)
a、 href=url;
a、 下载='发票';
文件.正文.附件(a);
a、 单击();
setTimeout(函数(){
文件.body.removeChild(a);
window.URL.revokeObjectURL(URL);
}, 0);
}
创建的Blob的编码似乎存在一些问题。如果我从Postman调用此端点并选择“保存响应”,然后选择“保存到文件”,我会得到正确的pdf。当我使用提供的代码时,文件似乎编码错误(用vim打开的文件通常具有相似的结构,但符号不同).在服务中,您可以使用如下httpOptions:
download() {
const httpOptions = {
responseType: 'blob' as 'json',
};
return this.http.get<any>(
ServerUrl + `/api/getfile`,
httpOptions
);
}
this.api.download().subscribe(
(idata) => {
let blob = new Blob([idata], { type: 'application/pdf'
});
var downloadURL = window.URL.createObjectURL(idata);
var link = document.createElement('a');
link.href = downloadURL;
link.download = 'invoice.pdf';
link.click();
},
async (err) => {
}
);