Element UI vue 上传文件、下载模板

样式

<el-upload
    class="upload-demo"
    action="/api/file/upload"
    :on-remove="handleRemove"
    multiple
    ref="uplpadFile"
    :limit="1"
    :on-exceed="handleExceed"
    :before-upload="beforeUpload"
    :file-list="fileList"
    accept="application/vnd.ms-excel"
  >
    <div>
      <el-button type="text" :loading="check">上传文件</el-button>
      <el-button type="text" @click.stop="downloadTpl">
        下载模板
      </el-button>
    </div>
    <div slot="tip" class="el-upload__tip">
      <div class="sms-upload-msg">1、支持Excel文件上传</div>
      <div class="sms-upload-msg">
        2、请将日期和时间相关列设置为【文本】类型再进行编辑
      </div>
    </div>
  </el-upload>

 // data 定义变量
fileList: []

JS 方法

// 上传的校验
beforeUpload(file) {
  this.check = true
  this.fileList = []
  let fd = new FormData()
  let size = parseFloat(file.size / 1048576)
  if (size > 10) {
    this.$message.error('上传文件最大不可超过10M')
    this.check = false
    return false
  }
  if (
    file.name.substring(file.name.lastIndexOf('.') + 1) !== 'xls' &&
    file.name.substring(file.name.lastIndexOf('.') + 1) !== 'xlsx'
  ) {
    this.$message.error('请上传Excel文件')
    this.check = false
    return false
  }
  fd.append('tag', 'robot-core')
  fd.append('files', file)
  if (size < 10) {
    this.$store.dispatch('uploadAudioFile', fd).then(res => {
      this.fileList.push({
        name: res.data.list[0].name,
        url: res.data.list[0].localPath + res.data.list[0].localName,
        sn: res.data.list[0].sn,
        size: res.data.list[0].size,
        localName: res.data.list[0].localName
      })
      this.templateForm.fileName = res.data.list[0].localName
      this.check = false
    })
  } else {
    this.$message.error('上传文件太大')
    this.check = false
  }
  return false
},
handleExceed(files, fileList) {
  this.$message.warning(
    `当前限制选择 1 个文件,本次选择了 ${
      files.length
    } 个文件,共选择了 ${files.length + fileList.length} 个文件`
  )
},
handleRemove(file, fileList) {
  this.fileList = []
  if (fileList.length === 1) {
    this.$confirm('确定删除吗?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(() => {
        this.fileList = []
      })
      .catch(() => {
        this.$message({
          message: '取消了删除',
          center: true
        })
      })
  }
},
posted @ 2022-12-09 08:54  DL·Coder  阅读(782)  评论(0编辑  收藏  举报