While I am able to successfully download a PDF using AngularJS in Chrome, it seems to encounter issues with the latest versions of FireFox, Internet Explorer 11, and Edge. It appears that a shim is required for IE9, although the current one doesn't seem to be effective. I have tried setting the response type to blob
and arraybuffer
, but this hasn't made a difference.
This contradicts what is indicated on caniuse regarding Blob URLs. Has anyone managed to get this working in IE9 and above, as well as the recent versions of FF? If so, could you please point out where I may be going wrong?
$http({
url: '/api/v1/download',
method: 'GET',
responseType: 'blob' // or 'arraybuffer'
}).then(function (response) {
var url = URL.createObjectURL(response.data);
anchor.href = downloadUrl;
anchor.download = filename;
anchor.target = '_blank';
anchor.click();
URL.revokeObjectURL(downloadUrl);
anchor = null;
}).catch(function (reason) {
console.log('FAIL', reason);
});
UPDATE
The currently suggested solution works for IE10, 11, Edge, and FF, while also remaining compatible with Chrome. However, IE9 requires another polyfill/shim, and Safari does not support the download attribute. Hence, I have left TODO stubs in these cases.
An updated version of the solution has been provided below with additional information added in the comments:
function performDownload(blob, filename) {
if(isIE() == 9) {
// TODO: polyfill/shim/other... change response type to?
}
else if (typeof window.navigator.msSaveBlob !== 'undefined') {
window.navigator.msSaveBlob(blob, filename);
}
else {
var URL = window.URL;
var downloadUrl = URL.createObjectURL(blob);
var anchor = document.createElement('a');
if(angular.isDefined(anchor.download)) {
anchor.href = downloadUrl;
anchor.download = filename;
anchor.target = '_blank';
document.body.appendChild(anchor);
anchor.click();
$timeout(function () {
URL.revokeObjectURL(downloadUrl);
document.body.removeChild(anchor);
anchor = null;
}, 100);
}
else {
// TODO: Safari does not support the download anchor attribute...
}
}
}