以角度5下载base64图像

时间:2018-10-09 13:23:13

标签: angular angular5

如何下​​载Angle 5中的图像 目前,我正在使用

中的saveAs函数
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');
}

在这种情况下,下载图像但打开错误。

1 个答案:

答案 0 :(得分:3)

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;
  }

首先,您需要将base64转换为Blob数据。

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();
    }
  }