In my Angular 7 application, I have the following code for downloading PDF on various platforms.
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();
}
}
);
The download works fine on all platforms except Chrome iOS. I mainly followed this link and a few other similar links.
I have also tried the following cases for Chrome iOS
const reader = new FileReader();
reader.onloadend = () => {
window.open(reader.result.toString());
};
reader.readAsDataURL(fileBlob);
Also replaced onloadend
with onload
above and tried both ways.
Plus I tried also with the code for Safari
, but that failed as well.
Any idea what I maybe missing here?