vue 上传本地文件后预览文件内容(支持txt,xlsx,doc)

 

 

 

 

安装依赖
npm install xlsx
npm i mammoth --save
引入
import XLSX from 'xlsx'
import * as mammoth from 'mammoth'

 

      <div style="display: flex; justify-content: center;">
        <div>
          <el-button id="file-button" type="primary" @click="handlePreview" style="width: 104px;margin-bottom: 10px">上传文件</el-button>
          <input type="file" name="file" style="display: none">
          <br>
          <el-button @click="showText()">显示文件内容</el-button>
        </div>
        <div>
          <textarea id="file-textarea" style="width: 500px;height: 500px" />
        </div>
      </div>

 

    handlePreview() {
      const input = document.querySelector('input[type=file]')
      input.click()
    },
    showText() {
      const input = document.querySelector('input[type=file]')
      if (!input) {
        this.$notify.error('请先上传文件')
      }
      const file = input.files[0]
      const type = file.name.substring(file.name.lastIndexOf('.') + 1)
      const reader = new FileReader()
      if (type === 'txt') {
        reader.readAsText(file)
        reader.onload = function() {
          if (reader.result) {
            document.querySelector('#file-textarea').innerHTML = reader.result
          }
        }
      }

      if (type === 'xlsx') {
        reader.readAsBinaryString(file)
        reader.onload = (ev) => {
          try {
            const data = ev.target.result

            const workbook = XLSX.read(data, {
              type: 'binary'
            })
            const wsname = workbook.SheetNames[0]
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname])// 生成json表格内容
            let str = ''
            ws.forEach((item) => {
              str += Object.values(item) + '\n'
            })
            document.querySelector('#file-textarea').innerHTML = str
          } catch (e) {
            return false
          }
        }
      }

      if (type === 'docx') {
        reader.readAsArrayBuffer(file)
        reader.onload = e => {
          const data = reader.result
          mammoth.extractRawText({ arrayBuffer: data }).then(r => {
            document.querySelector('#file-textarea').innerHTML = r.value
          })
        }
      }
    },

 

posted @ 2022-08-16 18:03  Stitchhhhh  阅读(2419)  评论(0编辑  收藏  举报