当前位置:   article > 正文

前端JS 实现文件Url、base64、File、Blob、ArrayBuffer相互转换方法_把files对象转为base64

把files对象转为base64

常见格式介绍

file对象 转换为 base64

let reader = new FileReader();
reader.readAsDataURL(file[0])
console.log(reader)
  • 1
  • 2
  • 3

base64 转换为 Blob

base64ToBlob(urlData) {
  let arr = urlData.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 });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

base64 转换为 file

base64toFile(dataurl, fileName) {
  let arr = dataurl.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 File([u8arr], fileName);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

Blob 转换为 blob地址

BlobToBlobURL(BlobFile,type) {
  let blob = new Blob([BlobFile], { type : type });// 图片:"image/jpeg"
  const blobUrl = URL.createObjectURL(blob);
  return blobUrl ;
}
  • 1
  • 2
  • 3
  • 4
  • 5

blob 转换为 ArrayBuffer

blobToArrayBuffer(){
let blob = new Blob([1,2,3,4])
let reader = new FileReader();
reader.onload = function(result) {
    console.log(result);
}
reader.readAsArrayBuffer(blob);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

buffer转换为 Blob

let blob = new Blob([buffer])
  • 1

图片URL 转换为 blob和base64

urlToBlobBase64(imgUrl) {
  return new Promise((resolve) => {
    window.URL = window.URL || window.webkitURL;
    var xhr = new XMLHttpRequest();
    xhr.open("get", imgUrl, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status == 200) {
        var blob = this.response;
        let oFileReader = new FileReader();
        oFileReader.onloadend = function (e) {
          resolve({ blob, base64: e.target.result });
        };
        oFileReader.readAsDataURL(blob);
      } else {
        reject(new Error("异常"));
      }
    };
    xhr.send();
    xhr.onerror = () => {
      reject(new Error("异常"));
    };
  });
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

Blob 转 base64

 function blobToDataURI(blob,callback) {
   var reader = new FileReader();
   reader.readAsDataURL(blob);
   reader.onload = function (e) {
     callback(e.target.result);
   };
 }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
// 调用
 blobToDataURI(blobData, function (result) {
    console.log(result);
});
  • 1
  • 2
  • 3
  • 4
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/IT小白/article/detail/145181
推荐阅读
相关标签
  

闽ICP备14008679号