Home > Web Front-end > JS Tutorial > JavaScript html5 sample code using FileReader to implement upload function

JavaScript html5 sample code using FileReader to implement upload function

黄舟
Release: 2017-03-24 15:05:01
Original
1439 people have browsed it

这篇文章主要为大家详细介绍了JavaScript html5利用FileReader实现上传功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了H5利用FileReader上传文件的具体代码,供大家参考,具体内容如下

1. Html部分

<h2>文件上传演练</h2> 
 <p id="result"> 
  <!-- 这里用来显示读取结果 --> 
  <p id="inResult"> 
  <p id="inImgs"></p> 
  <p id="imgInfo"></p> 
  </p> 
 </p> 
  
 <input type="text" id="txtImgSrc" /><!--显示图片信息--> 
 <input type="button" id="btnRemove" /> 
 <button id="btnBrowse" onClick="onFile()">Browse...</button> 
 <input type="file" id="file_input" />
Copy after login

2. JS部分

<script type="text/javascript"> 
 var result = document.getElementById("result"); 
 var input = document.getElementById("file_input"); 
 var inResult = document.getElementById(&#39;inResult&#39;); 
  
 if(typeof FileReader === &#39;undefined&#39;){ 
  result.innerHTML = "抱歉,你的浏览器不支持 FileReader"; 
  input.setAttribute(&#39;disabled&#39;,&#39;disabled&#39;); 
 }else{ 
  input.addEventListener(&#39;change&#39;,readFile,false); 
 } 
 function onFile(){ 
  document.getElementById(&#39;file_input&#39;).click(); //打开<input type="file" id="file_input" /> 
  }    
     
 function readFile(){ 
  var file = this.files[0]; 
  var fsize = parseInt((file.size)/1024); //计算图片大小,默认是B,转换成KB 
  if(!/image\/\w+/.test(file.type)){ 
   alert("请确保文件为图像类型"); 
   return false; 
  } 
  var reader = new FileReader(); 
  reader.readAsDataURL(file); 
   
  reader.onload = function(e){ 
   //alert(this.result); 
   inImgs.innerHTML = &#39;<img src="&#39;+this.result+&#39;" alt="" width="198px" height="250px" id="img"/>&#39;; //显示图片 
   var arr = input.value.split(&#39;\\&#39;); //分割图片路径 
   document.getElementById(&#39;result&#39;).style.display="block"; 
   document.getElementById(&#39;txtImgSrc&#39;).value = arr[arr.length-1]; //取数组最后部分 - 图片名字.jpg 
   document.getElementById(&#39;imgInfo&#39;).innerHTML = arr[arr.length-1]+"<br/>("+fsize+"kb)"; //显示图片名字加图片大小 
   
  } 
 } 
</script>
Copy after login

3.图片测试

The above is the detailed content of JavaScript html5 sample code using FileReader to implement upload function. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template