读取本地文件 并更换 img 图片

<div class="form-group">
    <label class="col-sm-2 control-label">头像</label>
    <div class="col-sm-8">
        <label for="id_avatar"><img id="avatar-img" src="/static/img/default.png" alt=""></label>
        <input accept="image/*" type="file" name="avatar" id="id_avatar" style="display: none">
        <span class="help-block"></span>
    </div>
</div>
++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<script>
// 找到头像的input标签绑定change事件
$("#id_avatar").change(function () {
// 1. 创建一个读取文件的对象
var fileReader = new FileReader();
// 取到当前选中的头像文件
// console.log(this.files[0]);
// 读取你选中的那个文件
fileReader.readAsDataURL(this.files[0]); // 读取文件是需要时间的
fileReader.onload = function () {
// 2. 等上一步读完文件之后才 把图片加载到img标签中
$("#avatar-img").attr("src", fileReader.result);
};
});
</script>

猜你喜欢

转载自blog.csdn.net/weixin_42506747/article/details/81940089