Skip to content Skip to sidebar Skip to footer

Image To Base64 String To JSON Object

Hi I am trying to create a form for which a user will enter their information and a image. I want to send all the information at once with a JSON object back to the Node.js server.

Solution 1:

FileReader is async function. You will need to use a callback to access the result. Your return reader.result is doing nothing.

function getBase64(file, cb) {
   var reader = new FileReader();
   reader.readAsText(file);
   reader.onload = function () {
     console.log(reader.result);//outputs random looking characters for the image
     // Return the result in the callback
     cb(reader.result);
   };
   reader.onerror = function (error) {
     console.log('Error: ', error);
   };
}

function sendData( data ) {
    $.ajax({
        url: '/registerAccount',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(data),
        dataType: 'json',
        success: function(data){
            console.log("success");
            //self.location = "http://localhost:4007/";
        },
        error: function(xhr,status,error){
            console.log("error");
            console.log(error);
        }
    });
}

document.getElementById('register').addEventListener('click', function() {
  console.log("registering...");
  var files = document.getElementById('fileInput').files;
  var imag32;

  console.log(tempData);
  var usr = document.getElementById("username").value;
  console.log(usr);
  var email = document.getElementById("email").value;
  console.log(email);
  var pass1 = document.getElementById("password").value;
  console.log(pass1);
  var pass2 = document.getElementById("password_confirm").value;
  console.log(pass2);
  if(pass1===pass2){
      var data = {usr:usr,email:email,pass:pass1};
      if ( files.length > 0 ) {
         getBase64( files[0], function( result ) {
           data.img = result;
           sendData(data);
         } );
      } else {
         sendData(data);
      }
  }
});

Post a Comment for "Image To Base64 String To JSON Object"