我的 post 请求 ajax 无法 post base64 图片

Cant post base64 image on my post request with ajax

我用 json 发送图像时遇到问题,当在 api 中接收正文时,“profile_image”属性没有值,但它是假设来到base64的uri。

  function getBase64(file) {
    var reader = new FileReader();
    reader.onloadend = function () {
      reader.result;
    };
    reader.readAsDataURL(file);

    return reader.result;
  }

        var file = document.getElementById("imgid").files[0];
        var base64File = getBase64(file)

body = {
          profile_image: base64File,
          name: "test",
          age: 19
}

$.ajax({
            url:
              "api.com/user",
            type: "POST",
            dataType: "json",
            contentType: "application/json",
            data: JSON.stringify({ user: body }),
            cache: false,
            processData: false,
            success: function (response) {
              console.log(response);
            },
            error: function (error) {
              console.log(error);
              );
            },
          });

方法readAsDataURL是一个异步方法。 return 语句会使函数在 reader 完成提取之前结束。

var getBase64 = function (file) {
    return new Promise(function (resolve, reject) {
        var reader = new FileReader();
        reader.onloadend = function () {
            base64String = reader.result;
            resolve(reader.result);
        };
        reader.readAsDataURL(file);
    })
}

var file = document.getElementById("imgid").files[0];
getBase64(file).then((base64String) => console.log(base64String) )