【问题标题】:Attach image and send it via json in base64 encoding附加图像并以base64编码通过json发送
【发布时间】:2020-11-23 09:49:29
【问题描述】:

我需要创建附加图片的功能,并通过 base64 中的 JSON 发送它们。 但我无法从 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);
}

统一更新: 如果我试图在 push() 函数中使用 json,那么我会遇到同样的问题。并且添加 await 没有帮助。我会很感激提示如何在 push() 函数中显示 json?

【问题讨论】:

    标签: javascript json forms image base64


    【解决方案1】:

    根据评论更新答案。你可以参考sandbox上的例子

    请添加创建承诺以避免回调地狱。这里我已经承诺了 base46 函数。 Promisification

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

    这样

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

    【讨论】:

    • 在这个答案中描述的情况下,json 将是未定义的,对吧?而且我们只能在await construct_json(form, data =&gt; { return data; }); 中显示它,如果我想在代码的下方使用它怎么办?根本不可能吗?
    • 你可以使用 Promise 来避免回调地狱
    • 欢迎您!祝你有美好的一天!
    【解决方案2】:

    是的。当 reader.onload 方法被调用时,您犯了一个错误。 You can find example here

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

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

    【讨论】:

    • 感谢您的回答!不幸的是,结果字符串仍然没有显示在 JSON 中。这段代码还有什么问题吗?
    • 你也忘了添加 Change 事件监听器。请检查沙箱。 :)。我也会上传答案。谢谢你,海伦
    • 请立即检查沙箱 ;)
    • 拜托,实际上您没有从 reader.onload 函数中获得任何回调。欢迎您。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多