Convert blob to base64

Convert blob to base64

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 is set to img src it displays the image:
var blob = items[i].getAsFile();
//var URLObj = window.URL || window.webkitURL;
//var source = URLObj.createObjectURL(blob);
//console.log(“image source=” + source);

var reader = new FileReader();
reader.onload = function(event){
}; // data url!
var source = reader.readAsBinaryString(blob);

The problem is with the the lower code, the source variable generated is null
Is there an easier way to do this with JQuery to be able to create Base64 String from Blob file as in the code above?


Solution 1:

 var reader = new FileReader();
 reader.onloadend = function() {
     base64data = reader.result;                

Form the docs readAsDataURL encodes to base64

Solution 2:

this worked for me:

var blobToBase64 = function(blob, callback) {
    var reader = new FileReader();
    reader.onload = function() {
        var dataUrl = reader.result;
        var base64 = dataUrl.split(',')[1];

Solution 3:

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:

  var fileInput = document.getElementById('myFileInputTag');
  var preview = document.getElementById('myImgTag');

  fileInput.addEventListener('change', function (e) {
      var url = URL.createObjectURL([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();
         url: '/PathToServer',
         method: 'POST',
         data: {
             imageString: base64Str
     success: function(data) { if(data && data.Success) {}},
     error: function(a,b,c){alert(c);}

Solution 4:

var audioURL = window.URL.createObjectURL(blob);
audio.src = audioURL;

var reader = new window.FileReader();
reader.onloadend = function () {
     base64data = reader.result;

Solution 5:

you can fix problem by:

var canvas = $('#canvas'); 
var b64Text = canvas.toDataURL();
b64Text = b64Text.replace('data:image/png;base64,','');
var base64Data = b64Text;

I hope this help you

Solution 6:

Most easiest way in a single line of code

var base64Image = new Buffer( blob, ‘binary’ ).toString(‘base64’);