先貼代碼,之後完善:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus®">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>js多種方式圖片預覽-持續更新</title>
</head>
<body>
<body>
<input type="file" id="file" value="選擇" accept="image/*">
<div style="width:300px;height:300px;border:1px solid #ccc">
<img id="img_show" src="" />
</div>
</body>
<script type="text/javascript" src="./jquery-3.1.1.min.js"></script>
<script type="text/javascript">
//設置自己的變量存儲區
var Util = {
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(typeof FileReader=='undefined'){//如果支持,typeOf返回的也是 Function
alert("您的浏覽器不支持html5 fileReader請更換浏覽器重試!");
return;
}
var reader = new FileReader();
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>
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。