美文网首页
blob base 64 与file格式相互转换

blob base 64 与file格式相互转换

作者: 爱学习的小仙女早睡早起 | 来源:发表于2022-08-31 16:53 被阅读0次

blob、 base 64 、file的格式长以下样子


image.png
blob 转 base 64
blobToDataURL(blob, callback) {
      let file = new FileReader();
      file.onload = function (e) {
        // console.log(e.target.result, "base64文件");
        callback(e.target.result);
      };
      file.readAsDataURL(blob);
},

// 调用
this.blobToDataURL(blob, (data) => {
        // console.log(data, "base64文件");
        let base64data = data.split(",")[1];
        
      });
base64转blob

function BaseBlob(baseFile) {
    let arr = baseFile.split(',')
    let mime = arr[0].match(/:(.*?);/)[1]
    let bstr = atob(arr[1])
    let n = bstr.length
    let u8arr = new Uint8Array(n)
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], {
        type: mime
    });
}
blob转file
function blobToFile(theBlob, fileName) {
    theBlob.lastModifiedDate = new Date();
    theBlob.name = fileName;
    return theBlob;
}

// Blob {size: 306788, type: "image/png"}
// var file = new File([blob], filename, {type: contentType, lastModified: Date.now()});

//  图片 - Blob转File
var result = new File([data], '文件名', {type: 'image/jpeg', lastModified: Date.now()});
console.log(result) // File {name: "123", lastModified: 1625712693925, lastModifiedDate: Thu Jul 08 2021 10:51:33 GMT+0800 (中国标准时间), webkitRelativePath: "", size: 306788, …}


// 文档pdf - blob转file
// const blob = // 拿到bolb
var file = new File([blob], `标题.pdf`, {type: 'application/pdf', lastModified: Date.now()});
let formDataPDF = new FormData();
formDataPDF.append('uploadFile', file);  // 这里的uploadFile由后端定义叫什么
console.log('uploadFile', formDataPDF.get("uploadFile"))
base64 转 file
// 把上面两个合在一起使用就是了
function BaseFile(file) {
    return blobToFile(BaseBlob(file))
}

通过文件地址获取base64

getBase64_byUrl(url, callback) {
      var Img = new Image(),
      dataURL = '';
      Img.src = url +"?v=" + Math.random();
      Img.setAttribute("crossOrigin", 'Anonymous') 
      Img.onload = function () { 
          var canvas = document.createElement("canvas"), 
          width = Img.width, 
          height = Img.height;
          canvas.width = width;
          canvas.height = height;
          canvas.getContext("2d").drawImage(Img, 0, 0, width, height); 
          dataURL = canvas.toDataURL('image/jpeg'); 
          callback ? callback(dataURL) : null; 
      };
    }

// 调用
getBase64(url, (data) => {    
 })



举例不同格式的文件上传

1、ele自带的上传组件,传的是file格式,参数名file也可以改写


image.png

相关文章

网友评论

      本文标题:blob base 64 与file格式相互转换

      本文链接:https://www.haomeiwen.com/subject/pdpdnrtx.html