Home > Web Front-end > JS Tutorial > body text

Code example of how to read files through the filereader interface in JavaScript

黄舟
Release: 2017-05-14 10:16:42
Original
1886 people have browsed it

This article mainly introduces in detail how to read files through the filereaderinterface, and use the readAsDataURL method to preview images The related methods have certain reference value. Interested friends can refer to

Use the readAsDataURL method of the FileReader interface to preview the image.

Source code:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 
<title>通过filereader接口读取文件</title> 
<script type="text/javascript"> 
function readAsDataURL() 
{ 
  if(typeof FileReader==&#39;undifined&#39;) //判断浏览器是否支持filereader 
  { 
    result.innerHTML="<p>抱歉,你的浏览器不支持 FileReader</p>"; 
    return false; 
  } 
  var file=document.getElementById("imagefile").files[0]; 
  if(!/image\/\w+/.test(file.type)) //判断获取的是否为图片文件 
  { 
    alert("请确保文件为图像文件"); 
    return false; 
  } 
  var reader=new FileReader(); 
  reader.readAsDataURL(file); 
  reader.onload=function(e) 
  { 
    var result=document.getElementById("result"); 
    result.innerHTML=&#39;<img src="&#39;+this.result+&#39;" alt=""/>&#39; 
  } 
   
} 
</script> 
</head> 
 
<body> 
<p> 
  <label>请选择一个文件:</label> 
  <input type="file" id="imagefile" /> 
  <input type="button" value="读取图像" onClick="readAsDataURL();" /> 
</p> 
<p name="result" id="result"> 
  <!-- 这里用来显示图片结果--> 
</p> 
</body> 
</html>
Copy after login

The above is the detailed content of Code example of how to read files through the filereader interface in JavaScript. 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!