HTML 部分
<div class="upload">
<input type="file" name="file" id="file">
<img id="img" width="100%" height="100%"
src="https://dss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=4016333918,4269266815&fm=26&gp=0.jpg"
alt="">
</div>
CSS 部分
.upload {
width: 120px;
height: 120px;
border: 1px solid #eee;
overflow: hidden;
position: relative;
}
.upload input[name="file"] {
width: 100%;
height: 100%;
position: absolute;
padding-top: 200px;
z-index: 9;
}
JS 部分
document.getElementById("file").addEventListener("change", function () {
let file = document.getElementById('file').files[0]
var ftype = file.name.substring(file.name.lastIndexOf(".") + 1);
if (ftype == "jpg" || ftype == "png" || ftype == "jpeg" || ftype == "JPG") {
var size = file.size / 1024 / 1024;
if (size > 1) { // 1:单位M
alert("头像不能大于1M");
return false;
}
r = new FileReader();
r.onload = function () {
console.log(r.result) //r.result 即为base64编码
document.getElementById("img").src = r.result
}
r.readAsDataURL(file);
} else {
alert("头像格式不对,请重新选择!");
return false;
}
});