html5 FileReader讀取文件

項目中須要讀取本地的txt文件,上網查了找到了FileReader,是經過H5的<input type="file">來操做的。css

下面是項目中的一個簡單應用:flex

1.HTML部分:spa

  <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>blog

2.css部分:ci

.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)';
}get

3.JS部分:input

$("#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);
}
});it

桌面建個txt,隨便輸點內容io

讀取console

預覽1:

找到文件:

點擊打開:

 

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

OvO完事

相關文章
相關標籤/搜索