【发布时间】: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