HTML5的FileReader实现本地图片预览

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title> 
</head>  
<body>  
    <input type="file" id="fileBox" multiple></input>  
    <input type="button" id="btn" value="读取"></input>  
    <div id="result"></div>  
</body>  
</html>  
<script type="text/javascript">  
var btn=document.getElementById('btn');  
  
btn.onclick=read;  
  
function read(){  
var fileBox = document.getElementById("fileBox");  
for (var i = 0; i <= fileBox.files.length - 1; i++)  
    {  
        var file=fileBox.files[i];  
        var reader=new FileReader();  
        reader.readAsDataURL(file);  
  
        reader.onload=function(){  
            var result=document.getElementById("result");  
            var imgE=document.createElement("img"); imgE.style='width:300px;height:400px;'; 
              
            imgE.src=this.result;  //this.result获取到img的URL
            result.appendChild(imgE);  
        };  
    };  
}  
</script>

 当选择一张图片,点击‘读取’时:

HTML5的FileReader实现本地图片预览

相关推荐