首页 > 解决方案 > 附加图像并以base64编码通过json发送

问题描述

我需要创建附加图片并通过 JSON 在base64. 但我无法从 FileReader 对象中获取结果字符串。如果您能告诉我如何解决此问题,我将不胜感激。

<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: 如果我试图在 push() 函数中使用 json,那么我会遇到同样的问题。并且添加 await 没有帮助。我会很感激提示如何在 push() 函数中显示 json?

标签: javascriptjsonformsimagebase64

解决方案


是的。当 reader.onload 方法被调用时,您犯了一个错误。你可以在这里找到例子

上传完成后,您忘记添加事件监听器和回调。请添加以下代码

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

推荐阅读