js读取文件内容

原理是,FileReader对象允许Web应用程序异步读取存储在用户计算机上的文件(或原始数据缓冲区)的内容,使用 File 或 Blob 对象指定要读取的文件或数据。其中 File 对象可以是来自用户在一个 input元素上选择文件后返回的FileList对象。
参考 https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader

  <style>
    .file-box{
      width: 100px;
      height: 100px;
      position: relative;
    }
    .file-box::before{
      content: '';
      display: block;
      width: 100%;
      height: 100%;
      border-radius: 4px;
      border: 1px dotted #999;
      background: #fff;
      position: absolute;
      top: 0;
      left: 0;
    }
    .input{
      width: 100%;
      height: 100%;
      opacity: 0;
    }
    .text{
      position: absolute;
      top: 30px;
      left: 0;
      right: 0;
      text-align: center;
    }
  </style>

  <div class="file-box">
    <input class="input" type="file" id="fileId" onchange="input()" draggable/>
  </div>

  <div id="content"></div>

脚本部分:


    async function input() {
      var fileInput = document.getElementById("fileId");
      const fileRes = await waitReader(fileInput.files[0])
      console.log(fileRes)
      document.getElementById('content').innerText = fileRes
    }
    function waitReader (file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()   // 新建一个FileReader
        reader.readAsText(file, 'UTF-8')  // 读取文件
        reader.onload = function (evt) {  // 读取完文件之后会回来这里 这是个异步
          const fileString = evt.target.result  // 读取文件内容
          fileString ? resolve(fileString) : reject(evt)
        }
      })
    }
posted @ 2022-10-07 23:51  晨の风  阅读(2002)  评论(0编辑  收藏  举报