<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
</style>
</head>
<body>
<div>
<input type="file" id="myimg"
οnchange="imgChange(this)"
accept="image/png,image/gif,image/jpeg"/>
<img width="300px" src="" alt="">
</div>
<script>
function imgChange(img) {
// 生成一个文件读取的对象
const reader = new FileReader();
reader.onload = function (ev) {
// base64码
var imgFile =ev.target.result;//或e.target都是一样的
document.querySelector("img").src= ev.target.result;
}
//发起异步读取文件请求,读取结果为data:url的字符串形式,
reader.readAsDataURL(img.files[0]);
}
</script>
</body>
</html>
来源:CSDN
作者:saturday-yh
链接:https://blog.csdn.net/qq_42092177/article/details/103474520