input file利用FileReader實現圖片上傳程式碼例項

螞蟻小編發表於2017-04-14

FileReader是HTML5新增,下面就是利用它實現圖片上傳的簡單程式碼。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
</head>
<style type="text/css">
.ImgBox img{
  width:100px;
  height:100px;
  margin-bottom:10px;
}
</style>
<body>
<div id="ImgBox" class="ImgBox"></div>
<input type="file" id="antzone">
</body>
<script type="text/javascript">
var fileBox = document.getElementById("antzone");
var ImgBox = document.getElementById("ImgBox");
fileBox.addEventListener("change",function(){
  var files_array = this.files;
  if(files_array[0].type.match(/image/)){
    read_image_file(files_array[0]);
  }
},false);
 
function read_image_file(file){
  var reader = new FileReader();
  reader.onload = function(e){
    var image_contents = e.target.result;
        var img = document.createElement("img");
        img.src = image_contents;
        ImgBox.innerHTML="";
        ImgBox.appendChild(img);
  };
  reader.readAsDataURL(file);
}
</script>
</html>

相關文章