js blob与base64互转、以及file和base64的相互转换

file和base64

1. file文件转换为base64,得到base64格式图片

var reader = new FileReader();
reader.readAsDataURL(this.files[0]);
reader.onload = function(){
    console.log(reader.result); //获取到base64格式图片
};

2. base64转换为file

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

运用案例:

<input type="file" name="" id="imgfile">
<script>
  var base64Img = '';
  document.getElementById('imgfile').onchange = function(){
      var fileReader = new FileReader();
      fileReader.readAsDataURL(this.files[0]);
      fileReader.onload = function(){
          base64Img = fileReader.result;
          console.log(dataURLtoFile(base64Img,'img11'))
      }
  }
   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});
  }    
</script>

blob和base64

1. base64 转换为blob

function dataURItoBlob(base64Data) {
    //console.log(base64Data);//data:image/png;base64,
    var byteString;
    if(base64Data.split(',')[0].indexOf('base64') >= 0)
        byteString = atob(base64Data.split(',')[1]);//base64 解码
    else{
        byteString = unescape(base64Data.split(',')[1]);
    }
    var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

    // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
    // var ia = new Uint8Array(arrayBuffer);//创建视图
    var ia = new Uint8Array(byteString.length);//创建视图
    for(var i = 0; i < byteString.length; i++) {
        ia[i] = byteString.charCodeAt(i);
    }
    var blob = new Blob([ia], {
        type: mimeString
    });
    return blob;
}

2.blob流转换为base64

function blobToDataURI(blob, callback) {
   var reader = new FileReader();
   reader.readAsDataURL(blob);
   reader.onload = function (e) {
       callback(e.target.result);
   }
}

运用案例:

<input type="file" id="imgfile">
<\img src="" id="img" alt=""> //这里图片总是转义,暂且这么写,知道是img就行
<\img src="" id="img2" alt="">
<script>
 document.getElementById('imgfile').onchange = function(){
     reads(this.files[0],function(base64Data){   //获取图片的base64格式,显示
         document.getElementById("img").src= base64Data;
         var blob = dataURItoBlob(base64Data); //转换为blob格式
         blobToDataURI(blob,function(result){    //blob格式再转换为base64格式
             document.getElementById('img2').src = result;
         })
     });
 }
 function reads(_file,callback){
     var reader = new FileReader();
     reader.readAsDataURL(_file);
     reader.onload = function(){
         callback(reader.result);
     };
 }
 function dataURItoBlob(base64Data) {
     //console.log(base64Data);//data:image/png;base64,
     var byteString;
     if(base64Data.split(',')[0].indexOf('base64') >= 0)
         byteString = atob(base64Data.split(',')[1]);//base64 解码
     else{
         byteString = unescape(base64Data.split(',')[1]);
     }
     var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];//mime类型 -- image/png

     // var arrayBuffer = new ArrayBuffer(byteString.length); //创建缓冲数组
     // var ia = new Uint8Array(arrayBuffer);//创建视图
     var ia = new Uint8Array(byteString.length);//创建视图
     for(var i = 0; i < byteString.length; i++) {
         ia[i] = byteString.charCodeAt(i);
     }
     var blob = new Blob([ia], {
         type: mimeString
     });
     return blob;
 }  

 function blobToDataURI(blob, callback) {
     var reader = new FileReader();
     reader.readAsDataURL(blob);
     reader.onload = function (e) {
         callback(e.target.result);
     }
 }
</script>

案例1:js将文件转成Base64编码字符串

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>简单的html5 File测试 for pic2base64</title>
<style>  *{margin:0;padding:0;box-s}  #txshow{width:300px;height:300px; border:none;}
</style>
<script>
    window.onload = function () {
        var input = document.getElementById("fielinput");
        var txshow = document.getElementById("txshow");
        if (typeof (FileReader) === 'undefined') {
            result.innerHTML = "抱歉,你的浏览器不支持 FileReader,请使用现代浏览器操作!";
            input.setAttribute('disabled', 'disabled');
        } else {
            input.addEventListener('change', readFile, false);
            txshow.onclick = function () { input.click(); }
        }
    }
    function readFile() {
        var file = this.files[0];
        //判断是否是图片类型
        /*if (!/image\/\w+/.test(file.type)) {
            alert("只能选择图片");
            return false;
        }*/
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = function (e) { 
            txshow.src = this.result; 
            document.getElementById("data").innerText=this.result.substring(this.result.indexOf(',')+1); 
        }
    }
</script>
</head>
<body>
  <input type="file" id="fielinput" />
  <img id="txshow" />
  <p/>解析之后的base64数据:<p/>
  <div id="data"></div>
</body>
</html>

参考:https://blog.csdn.net/qq_34664239/article/details/94595508

      https://www.cnblogs.com/webuserlast/p/4842498.html

posted @ 2022-11-17 22:03  土小狗  阅读(6126)  评论(0编辑  收藏  举报