在我的应用程序中,我需要通过调用 api 来下载 pdf 文件。该api返回一个octet-stream
数据,我将其转换为pdf并下载。我的下载和相关工作正常,但我发现生成的 PDF 似乎已损坏。打开 pdf 文档时,会记录一条错误消息,其中包含"Failed to load PDF document"
. 我知道 pdf 数据已损坏。我已经实现了相同的angular 1
工作正常,但我的Ionic 3
代码似乎是一个错误。
这是我的角度 1 代码。
$http({
method: 'POST',
url: baseurl + 'data/invoice',
responseType:"arraybuffer",
transformRequest: transformRequestAsFormPost,
withCredentials: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': AuthToken,
},
params: {
data_id: id,
}
}).success(function(data, status, headers, config) {
var arr = data;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(
new Blob([byteArray], { type: 'application/octet-stream' })
);
a.download ='MyFileName.pdf' ;
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}).error(function(error, status, headers, config) {
alert("Error")
});
我的 Ionic 3 代码是这样的。
http模块内部
fnPostData(method, token, parameters){
this.tokenString = "Bearer "+token;
this.postParams = parameters;
var headers = new Headers();
headers.append("Accept", 'application/json');
headers.set("Authorization", this.tokenString);
headers.set("Content-Type", 'application/x-www-form-urlencoded');
let options = new RequestOptions({
headers: headers
});
return Observable.create(observer => {
this.http.post(baseUrl + method, this.postParams, options)
.map(result => result)
.subscribe(result => {
console.log("API Result:", result);
observer.next(result);
}, error => {
observer.error(error);
});
});
}
在我的组件类里面
generateDataPdf(order) {
let isToken = 1;
this.asyncData.fnPostData('data/invoice?data_id='+order.id, this.token, isToken).subscribe((data) => {
if(data){
var arr = data;
var byteArray = new Uint8Array(arr);
var a = window.document.createElement('a');
a.href = window.URL.createObjectURL(
new Blob([byteArray], { type: 'application/octet-stream' })
);
a.download ='FileName.pdf';
// Append anchor to body.
document.body.appendChild(a);
a.click();
// Remove anchor from body
document.body.removeChild(a);
}else{
alert("Error");
}
},
(err) => {
alert("Error")
});
}
我知道我在 http 请求中遗漏了以下内容。
responseType:"arraybuffer",
transformRequest: transformRequestAsFormPost,
withCredentials: false,
是不是因为这个,我的pdf数据被破坏了?如果是,我如何将其添加到 http 请求中。