Dailycode.info

Short solution for short problems

Angular: download blob in IE11 not working.

I had an Angular 4 web app where the user could open a document coming as a blob from our DB. In IE11 this didn't work the normal way. The code looked like this:

try {
	let link = window.document.createElement('a');
	let blob = new Blob([data], { type: document.FileType });
	let url = window.URL.createObjectURL(blob);
	
	link.setAttribute('href', url);
	link.setAttribute('download', document.FileName);

	let event = window.document.createEvent('MouseEvents');
	event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	link.dispatchEvent(event);

	defer.resolve(true);
}
catch (ex) {
	self.logService.log(ex);
	defer.resolve(false);
}

The problem was that the link was not supposed to have the href and download attribute set for IE. Also the url had to be build up in a slightly different way using the msSaveOrOpenBlob:

try {
	let link = window.document.createElement('a');
	let blob = new Blob([data], { type: document.FileType });
	let url = null;

	if (navigator.msSaveBlob || navigator.msSaveOrOpenBlob) {
		url = navigator.msSaveOrOpenBlob(blob, document.FileName);
	} else {
		url = window.URL.createObjectURL(blob);
		link.href = url;
		link.setAttribute('download', document.FileName);
	}

	let event = window.document.createEvent('MouseEvents');
	event.initMouseEvent('click', true, true, window, 1, 0, 0, 0, 0, false, false, false, false, 0, null);
	link.dispatchEvent(event);

	defer.resolve(true);
}
catch (ex) {
	self.logService.log(ex);
	defer.resolve(false);
}

This check if (navigator.msSaveBlob || navigator.msSaveOrOpenBlob) will see if the browser needs to use a different way to open the BLOB. I believe this is specific for Microsoft browsers. More on this here. This worked for me, I hope it can help you.



blog comments powered by Disqus