Convert Base64 url to image file in Angular

1,583 阅读1分钟

把base64转成Blob格式

dataURItoBlob(dataURI) {
    const byteString = atob(dataURI.split(',')[1]);
    const arrayBuffer = new ArrayBuffer(byteString.length);
    const int8Array = new Uint8Array(arrayBuffer);
    for (let i = 0; i < byteString.length; i++) {
      int8Array[i] = byteString.charCodeAt(i);
    }
    const blob = new Blob([int8Array], { type: 'image/jpg' });
    return blob;
}

把base64 字符串转成 File

convertBase64toFile(base64) {
    const date = new Date().valueOf();
    const imageName = date + '.jpg';
    const imageBlob = dataURItoBlob(base64);

    const imageFile = new File([imageBlob], imageName, { type: 'image/jpg' });
    return imageFile;
}

Example

const base64 = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAgGBgcGB....'

const file = convertBase64toFile(base64);