• 微信公众号:美女很有趣。 工作之余,放松一下,关注即送10G+美女照片!

前端功能:Vue实现图片/文件的上传与内容解析

互联网 diligentman 3小时前 2次浏览

效果页面:

前端功能:Vue实现图片/文件的上传与内容解析

 效果描述:可以点击按钮选择规定的类型文件,也可以将文件拖到右侧后解析文件内容

实现代码:

1.自定义一个上方功能模块的组件(组件名UploadExcel.vue)

<template>
  <div class="drop">
    <input
      ref="excel-upload-input"
      class="excel-upload-input"
      type="file"
      accept=".xlsx, .xls"
      @change="handleClick"
    >
    <div class="left">
      <el-button :loading="loading" type="primary" @click="handleUpload">
        点击上传
      </el-button>
    </div>
    <div
      class="right"
      @drop="handleDrop"
      @dragover="handleDragover"
      @dragenter="handleDragover"
    >
      将文件托到此处
    </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, // 存储解析后的excel头部
        results: null // 存储解析后的excel列表
      }
    }
  },
  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()
      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)) {
        s
        this.$message.error(
          'Only supports upload .xlsx, .xls, .csv suffix files'
        )
        return false
      }
      this.upload(rawFile)
      e.stopPropagation()
      e.preventDefault()
    },
    handleDragover(e) {
      e.stopPropagation()
      e.preventDefault()
      e.dataTransfer.dropEffect = 'copy'
    },
    handleUpload() {
      this.$refs['excel-upload-input'].click()
    },
    handleClick(e) {
      const files = e.target.files
      const rawFile = files[0] // only use files[0]
      if (!rawFile) return
      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) {
        // 经过if判断,如果是false就对文件进行解析
        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)
      })
    },
    // 解析Excel的数据
    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;
}
.drop {
  border: 2px dashed #bbb;
  width: 600px;
  height: 160px;
  line-height: 160px;
  margin: 0px auto;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 5px;
  text-align: center;
  color: #bbb;
  .left {
    flex: 1;
    border-right: 1px dashed #bbb;
  }
  .right {
    flex: 1;
  }
}
</style>

2.全局注册后使用组件

<template>
  <div>
    <UploadExcel :before-upload="beforeUpload" :on-success="onSuccess" />
  </div>
</template>

<script>
export default {
  name: '',
  data() {
    return {}
  },
  computed: {},
  created() {},
  methods: {
    // 限制上传文件的大小和类型
    beforeUpload(file) {
      console.log(file)
      // 规定只能是.png类型的文件
      const ispng = file.type === 'image/png'
      // 规定所上传的文件不能>1M
      const is1M = file.size / 1024 / 1024 <= 1
      if (!ispng) {
        this.$message.error('请输入png格式图片')
      }
      if (!is1M) {
        this.$message.error('请上传1M以内大小的文件')
      }
      return ispng && is1M
    },
    // 读取上传xlsx文件的内容
    onSuccess({ header, results }) {
      console.log(header, 'header', results, 'results')
    }
  }
}
</script>
<style lang="less" scoped></style>


程序员灯塔
转载请注明原文链接:前端功能:Vue实现图片/文件的上传与内容解析
喜欢 (0)