文件上传组件

本文介绍了一个在项目中常用的封装文件上传组件,专用于处理.xlsx和.xls文件,包括上传前检查、进度提示和解析xlsx数据的功能。使用了npm包xlsx进行数据处理。

项目中经常要用到文件上传,下面是一个封装好的文件上传的组件,重要的部分添加了相应的备注。

<template>
  <div class="uploadExcel">
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
    <div class="left">
      <el-button
        type="primary"
        :loading="loading"
        @click="handleUpload"
      >点击上传</el-button>
    </div>
    <div
      class="right"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"

    >
      <span>将文件拖到此外</span>
    </div>

  </div>
</template>

<script>
import XLSX from 'xlsx'

export default {
  name: 'UploadExcel',
  props: {
    beforeUpload: Function, // eslint-disable-line  上传前,它允许 上传,上传才执行
    onSuccess: Function // eslint-disable-line  解析成功后的处理
  },
  data() {
    return {
      loading: false,
      excelData: {
        header: null,
        results: null
      }
    }
  },
  methods: {
    generateData({ header, results }) {
      this.excelData.header = header
      this.excelData.results = results
      // 如果有onSuccess方法就执行onSuccess({header,results})
      this.onSuccess && this.onSuccess(this.excelData)
    },
    handleDrop(e) {
      e.stopPropagation()
      e.preventDefault()
      //   如果文件正处于读取中,就return
      if (this.loading) return
      //   拿到拖入的文件数组
      const files = e.dataTransfer.files
      //   读取文件数组长度
      if (files.length !== 1) {
        this.$message.error('Only support uploading one file!')
        return
      }
      //   获取第一个文件
      const rawFile = files[0] // only use files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    // 阻止默认事件(当我们拖动文件到浏览器窗口时,浏览器会默认打开一个新窗口,打开文件,不会立即解析文件,所以 @drop @dragover @dragenter 都需要阻止默认行为)
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files // [文件1,文件2]
      const rawFile = files[0] // only use files[0]
      // 没有选择上传文件 直接return
      if (!rawFile) return
      // 如果选择了上传文件,执行upload
      this.upload(rawFile)
    },
    upload(rawFile) {
      this.$refs['excel-upload-input'].value = null // fix can't select the same excel
      // 如果没有通过props传参beforeUpload,它的值默认是undefined,转换成boolean就是false
      if (!this.beforeUpload) {
        // 解析文件
        this.readerData(rawFile)
        return
      }
      // 如果你传入了beforeUpload,执行该方法后,它要返回一个boolean值,boolean为true才开始解析
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    // 解析excel数据
    readerData(rawFile) {
      this.loading = true
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          this.generateData({ header, results })
          this.loading = false
          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    isExcel(file) {
      return /\.(xlsx|xls|csv)$/.test(file.name)
    }
  }
}
</script>

<style scoped lang="scss">
.excel-upload-input {
  display: none;
  z-index: -9999;
}
.uploadExcel {
  display: flex;
  width: 600px;
  height: 200px;
  margin: 0 auto;
  border: 1px dashed #ccc;
  .left {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    border-right: 1px dashed #ccc;
  }
  .right {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
/* .drop {
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0 auto;
  font-size: 24px;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  position: relative;
} */
</style>

调整页面布局,完善功能后使用组件,excel导入功能需要使用npm包xlsx,安装对应xlsx插件并注册后就可以啦~

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值