我正在尝试使用以下代码从api下载以字节数组形式返回的文件。但是在浏览器中,该文件有时仅下载,否则失败而没有错误。 这是代码:
this.service.getTerms(docId).subscribe(
response => {
var byteCharacters = atob(response);
var byteNumbers = new Array(byteCharacters.length);
for (var i = 0; i < byteCharacters.length; i++) {
byteNumbers[i] = byteCharacters.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
var blob = new Blob([byteArray], {type: 'application/pdf'});
if(!this.platform.is('android') && !this.platform.is('ios')){
let fileObjectURL = URL.createObjectURL(blob);
let a = document.createElement("a");
document.body.appendChild(a);
a.href = fileObjectURL;
a.download = docName+'.pdf';
a.click();
window.URL.revokeObjectURL(fileObjectURL);
}
let fileName = docName;
let filePath = this.file.documentsDirectory;
if(this.platform.is('android')){
filePath = this.file.externalDataDirectory;
}
this.file.writeFile(filePath , fileName+'.pdf',blob,{replace:true})
.then(success => {
this.fileOpener.open(filePath+fileName+'.pdf', 'application/pdf')
.then((success) => {
this.loading.dismiss();
})
.catch(error => {
this.loading.dismiss();
});
})
.catch(error => {
this.loading.dismiss();
});
},
(error) => {
this.util.displayAlert(this.translations.ERROR,error.json().ReturnMessage);
this.loading.dismiss();
}
)
我正在使用Ionic版本3.19.1。