之前为了实现这个图片预览的功能,我在选择图片之后就将其添加到项目中,再查询出来(捂脸),后来发现有更简单方便的方法:使用FileReader接口
FileReader 对象
允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对 象指定要读取的文件或数据。
我们先建好HTML页面
<input type="file" name="addimg" onchange="showimgfun(this)" id="addimg" />
<img id="showimg" style="max-height: 600px;max-width: 600px;margin-top: 20px;" />
在使用FileReader
之前,先测一下当前浏览器是否支持FileReader
接口
if(typeof FileReader == 'undefined'){
alert("当前浏览器不支持FileReader接口");
}
浏览器没有提示,说明是支持的,然后就可以开始写showimgfun()方法了
function showimgfun(obj){
var file = obj.files[0];
console.log(obj);console.log(file);
我们可以console看一下传进来的值
var reader = new FileReader();//创建FileReader对象
reader.onload = function(e){
//onload是读取成功的事件
var img = document.getElementById('showimg');
//将返回的结果赋值给img标签的src属性
img.src=e.target.result;
//target可以返回事件的目标节点
}
reader.readAsDataURL(file);//readAsDataURL方法可以将读取到的文件编码成Data URL
}
onload
是当FileReader读取成功后触发
的事件,除此之外还有以下几个事件:
- onloadstart:开始读取时触发
- onprogress:读取中触发
- onabort:读取中断时触发
- onerror:读取出现异常时触发
测试一下效果