Download a base64 encoded file, then save it in JavaScript

 First we need to convert the base64 string (assume fetched from an http request) to a Blob.


b64toBlob (b64Data: string, contentType = '', sliceSize = 512) {
    const byteCharacters = atob(b64Data);
    const byteArrays = [];
 
    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
      const slice = byteCharacters.slice(offset, offset + sliceSize);
 
      const byteNumbers = new Array(slice.length);
      for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i);
      }
 
      const byteArray = new Uint8Array(byteNumbers);
      byteArrays.push(byteArray);
    }
 
    const blob = new Blob(byteArrays, {type: contentType});
    return blob;
}

Then we need to create a temporary anchor element and simulate click.


const file = this.b64toBlob(res, 'text/xml', 512); 
const a = document.createElement('a'),
url = URL.createObjectURL(file);
a.href = url;
a.download = `out.xml`;
document.body.appendChild(a);
a.click();
setTimeout(
    function () {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
    }, 
    0
);

Post a Comment

Previous Post Next Post