多种方式实现js图片预览
先贴代码,之后完善:
<!doctypehtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<metaname="Generator"content="EditPlus®">
<metaname="Author"content="">
<metaname="Keywords"content="">
<metaname="Description"content="">
<title>js多种方式图片预览-持续更新</title>
</head>
<body>
<body>
<inputtype="file"id="file"value="选择"accept="image/*">
<divstyle="width:300px;height:300px;border:1pxsolid#ccc">
<imgid="img_show"src=""/>
</div>
</body>
<scripttype="text/javascript"src="./jquery-3.1.1.min.js"></script>
<scripttype="text/javascript">
//设置自己的变量存储区
varUtil={
file:$("#file"),
image_show:$("#img_show")
}
Util.file.onchange=function(f){
if(this.files[0].type.indexOf('image')<0){
alert("请选择图片文件!");
return;
}
if(this.files[0].size/1024>5*1024){
alert("图片过大,请选择5M以下的文件");
return;
}
if(typeofFileReader=='undefined'){//如果支持,typeOf返回的也是Function
alert("您的浏览器不支持html5fileReader请更换浏览器重试!");
return;
}
varreader=newFileReader();
reader.readAsDataURL(this.files[0]);//这里传的是一个blob,其实file对象就是继承自bolob
reader.onload=function(e){
console.log(reader.result);//这里拿到的是一个base64编码后的图片
Util.image_show.src=reader.result;
}
};
</script>
</html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。