html5 FileReader读取文件

项目中需要读取本地的txt文件,上网查了找到了FileReader,是通过H5的<input type="file">来操作的。

下面是项目中的一个简单应用:

1.HTML部分:

  <div style="display: flex;flex-direction: row;justify-content: space-around;align-items: center;">
    <span class="file" ><span>录入指纹</span>
    <input type="file" id="fingerPick" ></span>
    <textarea id="finger" placeholder="请录入指纹信息" readonly="readonly" class="je-textarea" style="min-height: 60px;"></textarea>
  </div>

2.css部分:

.file{
width: 100px;
text-align: center;
font-size: 14px;
border-radius: 4px;
position: relative;
display: inline-block;
overflow: hidden;
height: 34px;
line-height: 34px;
margin:-19px 5px;
color: #fff;
background-color: #0074d9;
border-color: #0074d9;
}
.file #fingerPick {
height: 34px!important;
line-height: 34px!important;
position: absolute;
left: 0px;
top: 0px;
opacity: 0;
-ms-filter: 'alpha(opacity=0)';
}

3.JS部分:

$("#fingerPick").click(function() {
  var fingerPick =document.getElementById("fingerPick");
  var finger =document.getElementById("finger");
  fingerPick.addEventListener('change', function(e){
    handFile(e.target.files[0]);
  });
  function handFile(file){
  var reader = new FileReader();
  reader.onload = function(e){
  finger.value = e.target.result;
  console.log(finger.value)
};
 reader.readAsText(file);
}
});

桌面建个txt,随便输点内容

读取

预览1:

找到文件:

点击打开:

······································

OvO完事

猜你喜欢

转载自www.cnblogs.com/xgxm13/p/9377052.html