Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

download base64 image in angular 5

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.

like image 636
M.Bilal Murtaza Avatar asked Oct 09 '18 13:10

M.Bilal Murtaza


1 Answers

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();
    }
  }
like image 122
Suresh Kumar Ariya Avatar answered Sep 26 '22 21:09

Suresh Kumar Ariya