javascript - 附加图像并以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?
解决方案
是的。当 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);
});
}
推荐阅读
- git - 在文件中显示差异但不允许 git 合并它们
- python - 如何在scrapy中将参数传递给pipelines.py?
- json - 反序列化之前值的 JSON 转义引号
- django - Django shell 不断失去与数据库的连接
- angular - 如果从订阅中显示,Ngx-Bootstrap 模式不会刷新数据更改
- angular - 以 DD-MM-YYYY 格式向 formControl MatDatePicker 的角度返回日期
- makefile - Make:动态执行规则
- python - 尝试使用 Python SQLAlchemy 在 Denodo 中执行查询时出错
- php - Laravel:如何在内核调度程序中引导我的模块
- opengl - PathTracing ShadowRay 的问题,球体全黑