Convert blob to base64

后端 未结 9 2020
无人共我
无人共我 2020-11-22 13:12

This is a snippet for the code that I want to do Blob to Base64 string:

This commented part works and that when the URL generated by this i

相关标签:
9条回答
  • 2020-11-22 13:39
    function bufferToBinaryString(arrayBuffer){
        return String.fromCharCode(...new Uint8Array(arrayBuffer));
    }
    (async () => console.log(btoa(bufferToBinaryString(await new Response(blob).arrayBuffer()))))();
    

    or

    function bufferToBinaryString(arrayBuffer){
        return String.fromCharCode(...new Uint8Array(arrayBuffer));
    }
    new Response(blob).arrayBuffer().then(arr_buf => console.log(btoa(bufferToBinaryString(arr_buf)))))
    

    see Response's constructor, you can turn [blob, buffer source form data, readable stream, etc.] into Response, which can then be turned into [json, text, array buffer, blob] with async method/callbacks.

    edit: as @Ralph mentioned, turning everything into utf-8 string causes problems (unfortunately Response API doesn't provide a way converting to binary string), so array buffer is use as intermediate instead, which requires two more steps (converting it to byte array THEN to binary string), if you insist on using native btoa method.

    0 讨论(0)
  • 2020-11-22 13:43
     var reader = new FileReader();
     reader.readAsDataURL(blob); 
     reader.onloadend = function() {
         var base64data = reader.result;                
         console.log(base64data);
     }
    

    Form the docs readAsDataURL encodes to base64

    0 讨论(0)
  • 2020-11-22 13:51

    So the problem is that you want to upload a base 64 image and you have a blob url. Now the answer that will work on all html 5 browsers is: Do:

      var fileInput = document.getElementById('myFileInputTag');
      var preview = document.getElementById('myImgTag');
    
      fileInput.addEventListener('change', function (e) {
          var url = URL.createObjectURL(e.target.files[0]);
          preview.setAttribute('src', url);
      });
    function Upload()
    {
         // preview can be image object or image element
         var myCanvas = document.getElementById('MyCanvas');
         var ctx = myCanvas.getContext('2d');
         ctx.drawImage(preview, 0,0);
         var base64Str = myCanvas.toDataURL();
         $.ajax({
             url: '/PathToServer',
             method: 'POST',
             data: {
                 imageString: base64Str
             },
         success: function(data) { if(data && data.Success) {}},
         error: function(a,b,c){alert(c);}
         });
     }
    
    0 讨论(0)
提交回复
热议问题