element-ui的upload上传封装组件

<template>
  <div>
    <input ref="excel-upload-input" class="excel-upload-input" type="file" accept=".xlsx, .xls" @change="handleClick">
    <div class="drop" @drop="handleDrop" @dragover="handleDragover" @dragenter="handleDragover">
      拖拽excel文件到此处 或者
      <el-button :loading="loading" style="margin-left:16px;" size="mini" type="primary" @click="handleUpload">
        浏览
      </el-button>
    </div>
  </div>
</template>
<script>
import XLSX from 'xlsx'
import { fasong } from '@/api/home'
export default {
  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
      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('只支持单个文件上传!')
        return
      }
      const rawFile = files[0]

      if (!this.isExcel(rawFile)) {
        this.$message.error('只支持.xlsx, .xls, .csv 格式文件')
        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

      if (!this.beforeUpload) {
        this.readerData(rawFile)
        return
      }
      const before = this.beforeUpload(rawFile)
      if (before) {
        this.readerData(rawFile)
      }
    },
    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' })
          //获取excel表格  第一个 通过更改 可获取其他表
          const firstSheetName = workbook.SheetNames[0]
          const worksheet = workbook.Sheets[firstSheetName]
          const header = this.getHeaderRow(worksheet)
          const results = XLSX.utils.sheet_to_json(worksheet)
          //results为解析完后的表格内容,可作为发送给后端的格式
          fasong(results).then((res) => { console.log(res) }, (que) => { console.log(que) })

          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>
.excel-upload-input {
  display: none;
  z-index: -9999;
}

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,下面是一个使用 Element UI 二次封装Upload 上传组件的示例代码: ``` <template> <div> <el-upload :action="uploadUrl" :headers="headers" :data="formData" :multiple="multiple" :show-file-list="showFileList" :limit="limit" :on-exceed="onExceed" :before-upload="beforeUpload" :on-success="onSuccess" :on-error="onError" :on-progress="onProgress" > <el-button type="primary" :disabled="uploading">{{ buttonText }}</el-button> <div slot="tip" class="el-upload__tip">{{ tip }}</div> </el-upload> </div> </template> <script> export default { name: "MyUpload", props: { uploadUrl: { type: String, default: "" }, headers: { type: Object, default: () => ({}) }, formData: { type: Object, default: () => ({}) }, multiple: { type: Boolean, default: false }, showFileList: { type: Boolean, default: true }, limit: { type: Number, default: 0 }, buttonText: { type: String, default: "上传文件" }, tip: { type: String, default: "只能上传jpg/png文件,且不超过500kb" } }, data() { return { uploading: false }; }, methods: { onExceed(files, fileList) { this.$message.warning(`只能上传${this.limit}个文件`); }, beforeUpload(file) { const isJPG = file.type === "image/jpeg" || file.type === "image/png"; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error("上传图片只能是 JPG/PNG 格式!"); return false; } if (!isLt500K) { this.$message.error("上传图片大小不能超过 500KB!"); return false; } return true; }, onSuccess(response, file, fileList) { this.uploading = false; this.$emit("upload-success", response, file, fileList); }, onError(err, file, fileList) { this.uploading = false; this.$emit("upload-error", err, file, fileList); }, onProgress(event, file, fileList) { this.uploading = true; this.$emit("upload-progress", event, file, fileList); } } }; </script> <style> /* 可以根据自己的需要修改样式 */ .el-upload__tip { font-size: 14px; color: #999; margin-top: 10px; } </style> ``` 这个 Upload 组件支持以下 props: - `uploadUrl`:上传文件的接口地址 - `headers`:上传请求的 headers - `formData`:上传请求的 formData - `multiple`:是否支持多选文件 - `showFileList`:是否显示已上传文件列表 - `limit`:最多上传文件个数 - `buttonText`:上传按钮的文本 - `tip`:上传提示信息 这个 Upload 组件还支持以下事件: - `upload-success`:上传成功的回调函数,参数为 response、file 和 fileList - `upload-error`:上传失败的回调函数,参数为 err、file 和 fileList - `upload-progress`:上传进度的回调函数,参数为 event、file 和 fileList 使用示例: ``` <template> <div> <my-upload :upload-url="uploadUrl" :headers="headers" :form-data="formData" :multiple="multiple" :show-file-list="showFileList" :limit="limit" :button-text="buttonText" :tip="tip" @upload-success="onUploadSuccess" @upload-error="onUploadError" @upload-progress="onUploadProgress" ></my-upload> </div> </template> <script> import MyUpload from "@/components/MyUpload"; export default { components: { MyUpload }, data() { return { uploadUrl: "https://xxx.com/upload", headers: { token: "xxx" }, formData: { type: "avatar" }, multiple: false, showFileList: true, limit: 1, buttonText: "上传头像", tip: "只能上传jpg/png文件,且不超过500kb" }; }, methods: { onUploadSuccess(response, file, fileList) { console.log("上传成功", response, file, fileList); }, onUploadError(err, file, fileList) { console.log("上传失败", err, file, fileList); }, onUploadProgress(event, file, fileList) { console.log("上传进度", event, file, fileList); } } }; </script> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值