我们在javascript中读取文件的方法:
1.借用文件域上传你需要读取的文件
2.选择我们想要读取的文件,进行读取
3.把读取的文件内容渲染在页面内
文件读取内容的代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<input type="file" name="" id="" multiple/>
<div></div>
<img src="" width="200" height="300"/>
<!--1,上传文件借助于文件域-->
<script type="text/javascript">
var file=document.querySelector('input');
var div=document.querySelector('div');
var img=document.querySelector('img');
file.onchange=function(){
// 2, 选择我们需要的文件, 进行读取,
var reader=new FileReader(); // 用来读取本地文件
// 读取this.files[0]中的文件里面的内容
reader.readAsText(this.files[0]);
// reader.readAsDataURL(this.files[0]);
reader.onload=function(){
console.log(this.result);
// 3,把读取的文件内容显示在 页面中
// div.innerHTML=this.result;
// img.src=this.result;
}
}
</script>
</body>
</html>