您好我正在尝试创建一个用户将输入其信息和图像的表单。我想用JSON对象一次性将所有信息发送回Node.js服务器。要发送图像,我尝试将图像转换为base64字符串,并将该字符串放在json对象中。当我打印出来自文件阅读器的.result时,会正确地打印出我想要的数据。当我把它放在我的数据对象中时,它表示未定义。
我怎么能改变这个,所以我可以将这个字符串存储在我的json对象中的文件中,这样我就可以在我的服务器上使用它了?
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);
}
});
}
});
答案 0 :(得分:0)
FileReader
是异步功能。您将需要使用回调来访问结果。你的return reader.result
什么也没做。
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);
}
}
});