el-upload上传组件

多文件手动上传组件,限制最大文件数量/格式/大小

<template>
  <el-upload
    class="upload-demo"
    ref="uploadRef"
    action="#"
    :auto-upload="false"
    :on-change="handleChange"
    :before-upload="beforeUpload"
    :accept="accept"
    :http-request="handleUpload"
    :file-list="fileList">
    <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
    <div slot="tip" class="el-upload__tip">单个文件最大上传{{ limitMax.singleMax }}MB,全部文件最大上传{{ limitMax.allMax }}MB</div>
  </el-upload>
</template>
<script>
import axios from 'axios'
export default {
  name: 'uploadFile',
  props: {
    loadingBtn: { // 按钮loading
      type: Boolean,
      default: false
    },
    accept: { // 接受的文件类型
      type: String,
      default: '.doc, .docx, .xls, .xlsx, .txt, .pdf'
    },
    limitMax: { // 文件大小限制
      type: Object,
      default: ()=>{
        return {
          singleMax: 5,
          allMax: 20
        }
      }
    },
    limit: { // 文件数量限制
      type: Number,
      default: 4
    },
    fileParams: { // 接口其他参数
      type: String,
      default: 'upup'
    }
  },
  data() {
    return {
      dialogVisible: false,
      fileList: [],
      files: [],
      time: null
    }
  },
  methods:{
    handleUpload() {
      let formData = new FormData()
      this.files.map(item => {
        formData.append('file', item)
      })
      formData.append('fileParams', this.fileParams)
      const config = {
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded'
        }
      }
      axios.post('接口名', formData, config).then(res=>{
        this.$emit('fileData', res.data)
      }).catch(e =>{
        this.$message({
          type: 'error',
          message: '上传失败!'
        })
        console.log('err', e)
      }).finally(()=>{
        this.$emit('upload:loadingBtn', false)
      })
    },
    // 手动上传
    submitUpload() {
      if(this.files.length > 0) {
        clearTimeout(this.time)
        this.time = setTimeout(()=>{
          this.time = null
          this.handleUpload()
        })
      } else {
        this.$message({
          type: 'warning',
          message: '请先上传附件!'
        })
      }
    },
    // 文件改变
    handleChange(file, fileList) {
      if(file.status === 'ready') {
        if(fileList.length > 4) {
          fileList.splice(0,1)
        }
        let files = []
        fileList.forEach(item => {
          files.push(item.raw)
        })
        this.files = files
      }
    },
    // 上传前验证
    beforeUpload(file) {
      const filename = file.name
      const type = filename.substring(filename.lastIndexOf('.'))
      const isType = this.accept.includes(type)
      const isLtM = file.size / 1024 / 1024 < this.limitMax.singleMax
      if(!isType) {
        this.$message({
          type: 'warning',
          message: '文件类型仅支持' + this.accept
        })
      }
      if(!isLtM) {
        this.$message({
          type: 'warning',
          message: '文件大小不能超过' + this.limitMax.singleMax + 'MB'
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
### 使用 `el-upload` 组件并设置 `auto-upload` 后获取上传文件 当使用 Element UI 的 `el-upload` 组件时,可以通过配置 `before-upload` 钩子函数来处理文件上传前的操作。即使设置了 `auto-upload="true"`,仍然可以在 `before-upload` 中访问到即将上传的文件对象。 #### 通过 `before-upload` 获取文件对象 在 `before-upload` 函数中,参数会接收到当前选中的文件对象。此函数可以用来执行一些预检逻辑,比如验证文件大小是否超过指定限制: ```javascript <template> <div> <el-upload :before-upload="handleBeforeUpload" action="" :on-success="handleSuccess" :file-list="fileList" :auto-upload="true"> <el-button type="primary">点击上传</el-button> </el-upload> </div> </template> <script> export default { data() { return { fileList: [] }; }, methods: { handleBeforeUpload(file) { const isLt10M = file.size / 1024 / 1024 < 10; if (!isLt10M) { this.$message.error('上传文件大小不能超过 10MB!'); } console.log('Selected File:', file); // 输出文件信息 return isLt10M; // 返回 true 或 false 来决定是否继续上传流程 }, handleSuccess(response, file, fileList) { console.log('Upload Success', response); } } }; </script> ``` 上述代码展示了如何利用 `before-upload` 方法拦截文件上传过程,并在此过程中打印出所选文件的信息[^1]。如果希望阻止自动上传行为,则可以让 `before-upload` 返回 `false`;反之则返回 `true` 让其正常提交给服务器[^2]。 #### 自定义触发上传时机 尽管启用了 `auto-upload=true`,也可以通过编程方式控制实际发起请求的时间点。例如,在某些情况下可能需要等待其他条件满足后再真正发送文件至服务端。此时可先禁用默认的立即上传功能 (`auto-upload=false`) 并手动调用 `.submit()` 方法实现延迟上传效果。 ```html <!-- 设置 auto-upload 属性为 false --> <el-upload ref="uploadRef" ... > ... <button @click="$refs.uploadRef.submit()">确认上传</button> ``` 这样就可以灵活调整何时启动真正的 HTTP 请求了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值