版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/tsoTeo/article/details/82772445
Html
<div>
<div style="position: relative;border: 5px solid lightblue;width: 150px;height:150px;margin: 5px auto;border-radius: 50%;">
<img src="/static/images/default.jpg" alt="选择并上传头像" id="avatar_img"
style="width: 140px;height: 140px;left:0;top: 0;border-radius: 50%;"/>
<input type="file" id="avatar_file" name="avatar_file"
accept="image/jpg,image/png,image/gif"
style="width: 100%;height:100%;opacity: 0;position: absolute;left:0;top: 0;"/>
</div>
<br/>
</div>
Script
<script>
// 头像预览
$("#avatar_file").change(function () {
// 获取上传文件对象
var file = $(this)[0].files[0];
// 读取文件URL
var reader = new FileReader();
reader.readAsDataURL(file);
// 阅读文件完成后触发的事件
reader.onload = function () {
// 读取的URL结果:this.result
$("#avatar_img").attr("src", this.result);
}
});
</script>