在我的 Angular 7 应用程序中,我有以下代码用于在各种平台上下载 PDF。
this.http.get('/api/url', {responseType: 'blob'}).pipe(map(res => {
return {
filename: 'filename.pdf',
data: res
};
}))
.subscribe(
res => {
const fileBlob = new Blob([res.data], {type: 'application/pdf'});
if (navigator && navigator.msSaveBlob) { // IE10+
navigator.msSaveBlob(fileBlob, res.filename);
} else if (navigator.userAgent.match('CriOS')) { // iOS Chrome
const reader = new FileReader();
reader.onloadend = () => {
window.location.href = reader.result.toString();
};
reader.readAsDataURL(fileBlob);
} else if (navigator.userAgent.match(/iPad/i) || navigator.userAgent.match(/iPhone/i)) { // iOS Safari and Opera
const url: string = URL.createObjectURL(fileBlob);
window.location.href = url;
} else {
const url: string = URL.createObjectURL(fileBlob);
const a: any = document.createElement('a');
document.body.appendChild(a);
a.setAttribute('style', 'display: none');
a.href = url;
a.download = res.filename;
a.click();
URL.revokeObjectURL(url);
a.remove();
}
}
);
下载在除 Chrome iOS 之外的所有平台上都能正常运行。我主要关注这个链接和其他一些类似的链接。
我还为 Chrome iOS 尝试了以下案例
const reader = new FileReader();
reader.onloadend = () => {
window.open(reader.result.toString());
};
reader.readAsDataURL(fileBlob);
也替换onloadend
为onload
上面并尝试了两种方式。另外,我也尝试了代码Safari
,但也失败了。
知道我在这里可能缺少什么吗?