论坛里有同学提出了这个问题,尝试了一下,中间走了一些弯路,最终实现方法很简单,还是记录下来,以备后用:
<!DOCTYPE html>
<html>
<head>
<title>img to base64</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
</head>
<body>
<img id="showImg" />
<input type="file" οnchange="changeFile(event);" />
</body>
</html>
<script type="text/javascript">
function changeFile(event) {
file = event.target.files[0];
var a = new FileReader();
a.onload = function (e) {
var base64Str = e.target.result;//获取base64
//下面是测试得到的base64串能否正常使用:
document.getElementById('showImg').src = base64Str;
}
a.readAsDataURL(file);
}
</script>