图像到Base64字符串到JSON对象 [英] Image to Base64 String to JSON Object

查看:574
本文介绍了图像到Base64字符串到JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我正在尝试创建一个表单,用户将为其输入信息和图像.我想一次将所有信息和JSON对象一起发送回Node.js服务器.为了发送图像,我正在尝试将图像转换为base64字符串,然后将该字符串放入json对象中.当我从文件阅读器打印出.result时,可以正确打印出我要在服务器上获取的数据.当我把它放在我的数据对象中时,它说它是未定义的.

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.

如何更改此设置,以便将文件中的字符串存储在json对象中,以便可以在服务器上使用它?

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是异步函数.您将需要使用回调来访问结果.您的return reader.result无所事事.

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);
      }
  }
});

这篇关于图像到Base64字符串到JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆