This question already has an answer here:
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. To send the image I am trying convert the image to a base64 string and place that string in the json object. When I print out the .result from the file reader is prints out correctly the data I want on my server. When I put it in my data object it says its undefined.
How might I change this so I can store that string from the file in my json object so I can use it on my server?
function getBase64(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function () {
console.log(reader.result);//outputs random looking characters for the image
return reader.result;
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
document.getElementById('register').addEventListener('click', function() {
console.log("registering...");
var files = document.getElementById('fileInput').files;
var imag32;
var tempData;
if (files.length > 0) {
tempData = getBase64(files[0]);
}
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,img:tempData};
console.log(data);// Prints: Object {usr: "", email: "", pass: "", img: undefined}
$.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);
}
});
}
});
FileReader
is async function. You will need to use a callback to access the result. Yourreturn reader.result
is doing nothing.