前端预览上传图片

1 本地预览上传图片
h5新增的FileReader构造函数
html结构

<input type="file" name="file" id="file">
    <div id="box"></div>

js代码

<script>
    let file = document.getElementById('file');
    let box = document.getElementById('box');
    file.onchange = function(){
        // 1 创建文件读取对象
        let reader = new FileReader();
        // 2 读取文件
        reader.readAsDataURL(this.files[0]);
        // 3 监听onload事件
        reader.onload = function(){
            // 3.1创建一个img标签
            let img = document.createElement('img');
            img.src = reader.result;
            console.log(reader.result);
            //  将元素添加到页面
            box.appendChild(img);
        }
    }
    
</script>

2 通过ajax向服务器请求预览上传图片
html 结构

			<label>请选择文件</label>
			<input type="file" id="file">
			<div class="padding" id="box">
				<!--<img src="" class="img-rounded img-responsive">-->
			</div>

js代码

 let file = document.getElementById('file');
 	 // 文件上传或修改时就会触发
    file.onchange = function() {
        // 创建一个空的FormDate表单对象
        let formDate = new FormData();
        // 文件域控件下有一个files属性,可以获取到文件的目录,是一个类对象
        // console.log(this.files[0]);
        // 把用户上传的数据追加到formDate对象中
        formDate.append('attrName',this.files[0]);
        // 发送请求
        let xhr = new XMLHttpRequest();
        xhr.open('post','http://localhost:3000/upload');
        xhr.send(formDate);
        xhr.onload = function(){
            // 获取服务器端返回的数据并转为json对象格式的数据
            let img_path = JSON.parse(xhr.responseText);
            // 创建图片标签
            let img = document.createElement('img');
            // 设置图片的路径
            img.src = img_path.path;
            // 图片从服务器加载完成会触发onload事件
            img.onload = function(){
                // 将图片显示在页面中
                box.appendChild(img);
            }
        }
    }
发布了17 篇原创文章 · 获赞 0 · 访问量 425

猜你喜欢

转载自blog.csdn.net/weixin_44805161/article/details/102611251