更新时间:2023-07-06 GMT+08:00
通过js将图片转成base64编码
下方示例代码通过js将图片转换成base64编码。功能如下:
- 在页面加载完成后,给id为imgUpload的文件输入框添加了一个onchange事件监听器,当用户选择了一张图片后,就调用getBase64函数。
- getBase64函数接收一个文件对象作为参数,然后创建一个FileReader对象,用来读取文件的内容。
- FileReader对象有一个onloadend事件,当文件读取完成后,就会触发这个事件。在事件处理函数中,可以通过reader.result获取到文件的数据URL,也就是一个以data:image/...;base64,开头的字符串。
- 为了得到纯粹的base64编码,需要将数据URL中的前缀部分去掉,这里用了一个正则表达式来实现。然后将得到的base64编码打印出来。
<html>
<head>
<script>
window.onload = function () {
document.getElementById('imgUpload').onchange = ($event) => {
const target = $event.target;
const file = target?.files[0];
getBase64(file);
}
}
function getBase64(file) {
const reader = new FileReader();
reader.onloadend = () => {
const imgBase64 = reader.result.replace(/^data:image\/.+?;base64,/, '');
console.log(imgBase64);
// 这个就是base64
};
reader.readAsDataURL(file);
}
</script>
<body>
<input accept="image/*" id="imgUpload" type="file" title="" />
</body>
父主题: API使用类