FileReader本地预览图片

<body>

        <p><label>请选择一个图像文件:</label><input type="file" id="demo_input" /></p>
<div id="demo_result"></div> <script type="text/javascript">
var result = document.getElementById("demo_result");
var input = document.getElementById("demo_input"); if(typeof FileReader === 'undefined'){
result.innerHTML = "<p class='warn'>抱歉,你的浏览器不支持 FileReader</p>";
input.setAttribute('disabled','disabled');
}else{
input.addEventListener('change',readFile,false);
} function readFile(){
var file = this.files[0];
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
result.innerHTML = '<img src="'+this.result+'" alt=""/>'
}
}
</script>
</body>

2,下面是我修改的,多图上传,本地预览:

<html>
<head>
<title>File Reader</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body{
text-align:center;
}
#demo_result img{
border:2px solid #369;
padding:3px;
}
p{
padding:20px 0;
}
.warn{
font-weight:bold;
color:red;
}
</style>
</head>
<body> <p><label>请选择一个图像文件:</label>
<input type="file" multiple="multiple" id="demo_input" />
</p>
<div id="demo_result"></div> <script type="text/javascript">
var result = document.getElementById("demo_result");
var input = document.getElementById("demo_input"); if(typeof FileReader === 'undefined'){
result.innerHTML = "<p class='warn'>抱歉,你的浏览器不支持 FileReader</p>";
input.setAttribute('disabled','disabled');
}else{
input.addEventListener('change',readFile,false);
} function readFile(){ for(var i=0;i<this.files.length;i++)
{
var file = this.files[i];
if(!/image\/\w+/.test(file.type)){
alert("请确保文件为图像类型");
return false;
}
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(e){
result.innerHTML+= '<img src="'+this.result+'" alt=""/>';
}
}
}
</script>
</body>
</html>
上一篇:廖雪峰老师的git在线教程


下一篇:SP Flash Tool使用异常集锦