download base64 image in angular 5

Issue

How to download image in angular 5
currently I am using saveAs function from

import { saveAs } from 'file-saver'

var blob = new Blob([this.attachment], { type: "image/png" });
console.log(blob);
console.log(window.btoa(blob.toString()));

if (this.attachment != null) {
  saveAs(blob, 'attachment');
}

In this case image download but error in open.

Solution

convertBase64ToBlobData(base64Data: string, contentType: string='image/png', sliceSize=512) {
    const byteCharacters = atob(base64Data);
    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;
  }

First, you need to convert base64 to Blob data.

const blobData = this.convertBase64ToBlobData(base64content);


    if (window.navigator && window.navigator.msSaveOrOpenBlob) { //IE
      window.navigator.msSaveOrOpenBlob(blobData, filename);
    } else { // chrome
      const blob = new Blob([blobData], { type: contentType });
      const url = window.URL.createObjectURL(blob);
      // window.open(url);
      const link = document.createElement('a');
      link.href = url;
      link.download = filename;
      link.click();
    }
  }

Answered By – Suresh Kumar Ariya

Answer Checked By – Katrina (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.