简体   繁体   中英

Attach image and send it via json in base64 encoding

I need to create the ability to attach pictures and send them via JSON in base64 . But I can't get the resulting string from FileReader object. I will be very grateful if you can tell me how to fix this.

<form>
    <label>Picture
         <input type="file" accept=".jpg, .jpeg, .png" name="picture" required>
    </label>
</form>
async function push() {
// some other actions here
    let form = new FormData(document.querySelector('form'));
    let json = construct_json(form);
//calls  of other functions
}

function getBase64(file) {
   let reader = new FileReader();
   reader.readAsDataURL(file);
   reader.onload = function () { // I think there is a mistake here.
     reader.result;
   };
}

function construct_json(form) {
    let json = {
        picture: getBase64(form.get('picture')),
    };

    return JSON.stringify(json);
}

UPD: If I'm trying to use json in the push() function then I get the same problem. And adding await doesn't help. I would be grateful for a hint how can I display json in the push() function?

Yes. You are making a mistake when reader.onload method gets envoke. You can find example here

You forget to addEventListener and callback when upload gets done. Please add the following code

window.addEventListener("change", push);

function getBase64(file, callback) {
  let reader = new FileReader();
  reader.onload = function(e) {
    // console.log(e.target);
    // I think there is a mistake here

    callback(e.target.result);
  };
  reader.onloadend = function(e) {
    return e.target.result;
  };
  return reader.readAsDataURL(file);
}

async function construct_json(form) {
  await getBase64(form.get("picture"), data => {
    let json = {
      picture: data
    };

    return JSON.stringify(json);
  });
}

Updating the answer based on comment. you can refer to the example on sandbox

Please add create a promise to avoid callback hell. Here I have promised the base46 Function. Promisification

const getBase64Promise = function (file) {
  return new Promise((resolve, reject) => {
    getBase64(file, (success,err) => {
        if(err) reject(err)
        else resolve(success);
    });
  });
};

Like this

async function construct_json(form, callback) {
  let data = await getBase64Promise(form.get("picture"));
    let json = {
      picture: data
    };
    return json;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM