DownloadFile(base64Stream, fileName) + IE Compatibility
Download a base64-encoded file in the browser via a hidden link, with legacy Internet Explorer compatibility.
2 min read
Updated
This module downloads a file from a base64-encoded payload by creating a hidden link, pointing it at a Blob URL and clicking it, so the browser handles the download itself. The implementation also carries the compatibility shims needed by older versions of Internet Explorer. The JavaScript source is preserved below.
donwload.js
javascript
/**
* Download a file by creating a hidden hyperlink DOM element in the current page,
* using file location as URL, and triggering a click on it.
* Confirmation dialog box and actual download is then handled directly by the navigator.
*
* @param {String} base64Stream Radix-64 binary data represented as an ASCII string
* @param {String} fileName Desired output file name
*/
export function downloadFile(base64Stream, fileName) {
saveByteArray([base64ToArrayBuffer(base64Stream)], fileName);
}
function base64ToArrayBuffer(base64) {
const binaryString = window.atob(base64);
const binaryLen = binaryString.length;
const bytes = new Uint8Array(binaryLen);
for (let i = 0; i < binaryLen; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes;
}
function saveByteArray(data, name) {
const blob = new Blob(data, { type : 'octet/stream' });
// Download for IE
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob, name);
return;
}
// Download for other browsers
const a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
const url = window.URL.createObjectURL(blob);
a.href = url;
a.download = name;
a.click();
window.URL.revokeObjectURL(url);
}