如何在javascript中从本地文件映像创建base64编码的字符串



我一直在尝试从本地机器转换图像文件,但似乎不适用。我不想使用输入上传图像,因为我只有生产中的图像路径,并且我想存储base64字符串。但如果有更好的方法我可以处理,那么我不介意


const reader = new FileReader();
const file = new File([imgUrl], { type: "image/png" });
console.log(file);
reader.addEventListener("load", function (e) {
console.log(e.currentTarget.result);
}, false);
const data = reader.readAsDataURL(file);
return data;
}
const img = "localhost:8080/start app abnner.png"; // my image path
getDataUrl(img);

关键是使用对象的结果属性(请参阅FileReader API。(

const reader = new FileReader()
reader.readAsDataURL(image) // assuming "image" is your file
reader.result // here is your base64 string

所以在你的情况下,它应该是:

const data = reader.readAsDataURL(file);
return data.result;

我曾经做过这样的事情,所以如果你想的话,我做了一个小插件:编码图像uri。它具有使用promise的优势,因此只有在转换完成且数据准备就绪时,您才能100%确定调用任何函数。

最新更新