【发布时间】:2023-03-16 11:15:02
【问题描述】:
在我的 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 之外的所有平台上都能正常运行。我主要关注this link 和其他一些类似的链接。
我也尝试过 Chrome iOS 的以下案例
const reader = new FileReader();
reader.onloadend = () => {
window.open(reader.result.toString());
};
reader.readAsDataURL(fileBlob);
还将onloadend 替换为上面的onload 并尝试了两种方式。
另外,我还尝试了Safari 的代码,但也失败了。
知道我在这里可能遗漏了什么吗?
【问题讨论】:
标签: ios angular google-chrome pdf-generation chrome-ios