el-upload自定义上传

        在自定义上传的场景下,我们通过使用  :http-request="handleFileUpload" 属性来指定自定义的上传函数, handleFileUpload将会负责实际处理文件的上传操作,并与后端进行交互。所以不需要指定具体的 action——指定文件上传的目标地址(后端接收文件的 API 地址),但需要将 action 设置为空字符串,是因为action属性为必传,需要传入一个值来满足校验要求。

    <el-upload
      ref="upload"
      class="upload-demo"
      :action="''"
      :on-remove="handleRemove"
      :before-upload="beforeUpload"
      :file-list="fileList"
      :http-request="handleFileUpload"
      accept=".xlsx,.XLSX,.xls,.XLS"
      :show-file-list="false"
    >
        <el-button slot="trigger" type="primary" size="mini">
            导入文件</el-button>
        <div slot="tip" class="el-upload__tip">只能上传xlsx/pngxls</div>
    </el-upload>

 :before-upload="beforeUpload"文件上传之前的自定义操作,如再次校验文件格式、大小。。。

   beforeUpload(file) {
      // 如下:在此再次校验文件格式,因为accept虽然会过滤其他文件格式,但若用户强制选择上传其他文件格式时。
      const testmsg = file.name.substring(file.name.lastIndexOf('.') + 1)
      const isXlsx = testmsg === 'xlsx' || testmsg === 'XLSX' || testmsg === 'xls' || testmsg === 'XLS'
      if (!isXlsx) {
        this.$message({
          message: '上传文件只能是 xlsx/xls 格式',
          type: 'warning'
        })
        return isXlsx //可以返回 false 阻止文件上传
      }
    },

:http-request="handleFileUpload":覆盖默认的上传行为,实现自定义文件上传函数,接收 `file` 参数。

handleFileUpload(file) {
    const formDate = new FormData()
    formDate.append('file', file.file)
    formDate.append('orderId', this.form.id)//上传的其他参数
    // 上传的接口需要定义Content-type
    axios({
        url:'/api/hasUploadfile',
        data:formDate,
        headers: { 'Content-type': 'multipart/form-data'},
        method: 'post',
    }).then((res) => { 
        this.fileList = []
        this.fileList.push(file.file)
        this.$message.success('上传成功!')
      }).catch((error) => {
        console.log(error, 'error')
        this.$refs.upload.clearFiles()
      })
    },

     :on-remove="handleRemove":删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。

    handleRemove(file, fileList) {
        this.fileList = fileList
    },

 

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值