我需要创建附加图片并通过中的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,则会遇到相同的问题。并且添加等待没有帮助。我将不胜感激如何在push()函数中显示json?
根据评论更新答案。您可以参考沙箱上的示例
请添加创建承诺以避免回调地狱。在这里,我答应了base46功能。承诺化
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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句