Fork me on GitHub

base64文件处理

base64 转换

  • base64 转图片

    1
    `data:${type};base64,`+code

    type 是文件类型,比如图片 image/png,image/jpeg,pdf:application/pdf

  • base64 转为 Blob 对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
    function dataURLtoBlob(dataurl) {
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
    }
    let blob = dataURLtoBlob(`data:${mimetype};base64,`+image)`)
  • blob 转为 File

    1
    2
    3
    4
    5
    6
     function blobToFile(theBlob, fileName){
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
    }
    var file = blobToFile(blob, imgName);
  • base64 转为 File 对象

    1
    2
    3
    4
    5
    6
    7
    8
    9
     function dataURLtoFile(dataurl, filename) {//将base64转换为文件
    var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
    while(n--){
    u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, {type:mime});
    }
    let file = dataURLtoFile(`data:${mimetype};base64,`+image)`,'PDF.pdf')
  • 转为 url

    1
    window.URL.createObjectURL(blob|file)
  • 下载

    1
    2
    3
    4
    let a=document.getElementById('download');
    let blob=dataURLtoBlob(`data:${image[0].mimetype};base64,`+image[0].image);
    a.download = image[0].name+'.pdf';
    a.href = window.URL.createObjectURL(blob)
-------------本文结束感谢阅读-------------