el-upload完成文件上传(大小不超过20MB,支持多选,最多不超过5个,超过5个隐藏上传按钮)

1、HTML代码

ini 复制代码
<el-form-item label="文件上传:" prop="files">
    <el-upload
      ref="upload"
      :headers="{
        accessToken: getToken(),
      }"
      class="upload-demo"
      :action="UPLOAD_ADDRESS"
      :before-upload="handleBeforeUpload"
      :on-success="handleSuccess"
      :on-remove="handleRemove"
      accept=".docx, .doc, .pdf, .ppt"
      :file-list="fileList"
      multiple
      :limit="5"
      :on-exceed="handleExceed"
    >
      <div class="upload_text">
        <el-button size="small" icon="el-icon-upload2">上传文件</el-button>
        <span slot="tip" class="el-upload__tip">至多上传5个,文件大小不超过20MB,支持扩展名:.doc .docx .pdf .ppt</span>
      </div>
    </el-upload>
</el-form-item>

注释:headers、action根据具体自己项目而定,上传接口不需要额外的请求头就不需要headers

2、Data

javascript 复制代码
data() {
    return {
      formData: {
        files: [],
      }, // 提交表单数据
      fileList: []
    }
  },

3、function

kotlin 复制代码
 // 1、文件上传之前的方法
    handleBeforeUpload(file) {
    //   console.log(file)
      // 如果验证失败,返回 false 来阻止文件上传
      const fileSize = Math.round(file.size / 1024 / 1024)
      if (fileSize > 20) {
        this.$message.error('上传文件过大,请重新选择')
        return false
      }
      return true // 如果验证通过,返回 true 来允许文件上传
    },
    
    // 2、文件上传成功要做的操作
    handleSuccess(res, file,fileList) {
      if (res.success) {
        this.$message.success('文件上传成功')
        this.formData.files.push({ fileName: res.data.fileName, url: res.data.url })
        this.$refs.formRef.clearValidate('files');
      } else {
        const index = fileList.indexOf(file);  
        if (index !== -1) {  
          fileList.splice(index, 1);  
        }  
        this.$message.error(res.msg)
      }
      if (this.formData.files.length >= 5) {
        this.$refs.upload.$el.querySelector('.el-upload').style.display = 'none' // 隐藏上传按钮
      }
    },
    
    // 3、移除已上传文件所做的操作
    handleRemove(file, fileList) {
      this.fileList = fileList
      const index = this.formData.files.findIndex(item => (item.url === file.response?.data.url || item.url === file.url)) // 确定删除的项
      if (index !== -1) {  
        this.formData.files.splice(index, 1) // 删除要删除的项
      }  
      if (this.formData.files.length < 5) {
        this.$refs.upload.$el.querySelector('.el-upload').style.display = 'block' // 开启上传按钮
      }
    },
    
    // 4、文件超出个数限制时的操作
    handleExceed() {
      this.$message.error('文件最多上传5个,请重新选择上传')
    },
相关推荐
m0_616188492 小时前
Vue3 中 Computed 用法
前端·javascript·vue.js
逍遥客.2 小时前
uniapp对接打印机和电子秤
javascript·vue.js·uni-app
boy快快长大4 小时前
【VUE】day01-vue基本使用、调试工具、指令与过滤器
前端·javascript·vue.js
JYeontu6 小时前
实现一个带@功能的输入框组件
前端·javascript·vue.js
一颗奇趣蛋6 小时前
vue-router的query和params的区别(附实际用法)
前端·vue.js
Nymph_Zhu7 小时前
vue3+antV G6节点与文本框实现
vue.js·element-plus·g6
lh_12547 小时前
VUE2脚手架的下载与安装
vue.js
cypking7 小时前
vue实现一个pdf在线预览,pdf选择文本并提取复制文字触发弹窗效果
前端·vue.js·pdf