elementui使用el-upload组件实现自定义上传

暴骏奇
2023-12-01

方式一:选择后自动上传

使用 http-request 覆盖默认的上传行为,可以自定义上传的实现
利用 before-upload 上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise且被 reject,则停止上传

template 部分

<el-upload
   class="pad"
   ref="upload"
   action="action"
   :http-request="uploadBpmn"
   :before-upload="beforeUpload">
   <el-button size="medium" type="primary" class="el-icon-upload"> 部署流程定义</el-button>
 </el-upload>

js 部分

beforeUpload (file) { // 上传文件之前钩子
  const type = file.name.split('.')[1]
  if (type !== 'bpmn') {
    this.$message({ type: 'error', message: '只支持bpmn文件格式!' })
    return false
  }
},
uploadBpmn (param) { // 部署流程定义(点击按钮,上传bpmn文件,上传成功后部署,然后重新加载列表)
  const formData = new FormData()
  formData.append('processDefinition', param.file) // 传入bpmn文件
  this.$API({
    name: 'deploy',
    data: formData,
    headers: {'Content-Type': 'multipart/form-data'}
  }).then(res => {
    if (res.data.code == 0) {
      this.$message({ type: 'success', message: res.data.msg })
    } else {
      this.$message({ type: 'error', message: res.data.msg })
    }
  }).catch(error => {
    this.$message({ type: 'error', message: error })
  }).finally(() => {
    this.getList()
  })
},

如果不想上传成功后显示上传文件列表,可以隐藏掉文件列表
可以在组件中设置 :show-file-list="false"
或者

::v-deep .el-upload-list {
  display: none !important;
}

方式二:选择后手动上传

<template>
  <div class="app-upload">
    <div class="upload-title">上传文件</div>
    <el-upload
      class="upload-demo"
      ref="uploadBox"
      drag
      action="action"
      :before-upload="beforeUpload"
      :http-request="upload"
      :auto-upload="false"
      multiple>
      <i class="el-icon-upload"></i>
      <div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
    </el-upload>
    <div class="upload-btn">
      <el-button type="primary" @click="sure" :loading="loading">确 定</el-button>
    </div>
  </div>
</template>

<script>
const formData = new FormData()
export default {
  data () {
    return {
      loading: false
    }
  },
  methods: {
    beforeUpload (file) { // 上传文件之前钩子
      formData.append('files', file)
    },
    upload () {
      this.loading = true
      this.$API({
        name: 'UploadResource',
        data: formData,
        params: {
          path: this.$route.query.path
        },
        requireAuth: true
      }).then (res => {
        if (res.data.code === 200) {
          this.$notify.success(res.data.msg)
        } else {
          this.$notify.error(res.data.msg)
        }
      }).catch(error => {
        this.$notify.error(error)
      }).finally(() => {
        this.loading = false
        this.reset()
      })
    },
    sure () {
      this.$refs.uploadBox.submit()
    },
  }
}
</script>

使用el-upload上传文件夹

只需要为 input 输入框设置 webkitdirectory 属性

  mounted() {
    if (this.$route.query.type === 'folder') {
      this.$nextTick(() => {
        document.querySelector('.el-upload__input').webkitdirectory = true
      })
    }
  },
 类似资料: