Element el-upload 上传组件,相关问题总结

最近在写 vue 上传文件组件,遇到了一些问题,及时总结:

<el-upload
   ref="uploadAttachment"
   class="input"
   :action="uploadUrl"
   :data="{ path: 'baojia', isdate: '1' }"
   :on-preview="handlePreviewGy"
   :on-change="(file, list) => handleChangeBoomGy(file, list, boom)"
   :on-success="(res, file, list) => handleSuccessBommGy(res, file, list, boom)"
   :before-upload="beforeUploadGy"
   :on-remove="(file, list) => removeBoomGy(file, list, boom)"
   :before-remove="beforeRemoveGy"
   :on-error="handleError"
   multiple
   :limit="3"
   :file-list="boom.gy_fileList?boom.gy_fileList:[]">
   <el-button size="small" type="primary">点击上传</el-button>
   <div slot="tip" class="el-upload__tip">不超过10M</div>
 </el-upload>
参数说明
action必选参数,上传的地址
data上传时附带的额外参数
on-preview点击文件列表中已上传的文件,触发函数,即点击已上传文件的效果
on-change添加文件、上传成功和上传失败时都会被调用
on-success文件上传成功时的钩子
before-upload上传文件之前的钩子,一般用作验证使用,例如大小,格式
on-remove文件列表移除文件时的钩子,删除后触发
before-remove删除文件之前的钩子,删除前触发,例如提示是否删除等等
on-error文件上传失败时的钩子
multiple是否支持多选文件
file-list上传的文件列表,上传成功后的数据需要赋值到这个字段内
limit最大允许上传个数

基本上常见也就是上面的字段,但是不仅仅就这么多,文档内有大量的字段,可以根据特殊定制

下面的js就是上面的对应方法,大家可以根据自己的需求去改

    handlePreviewGy(file) {
      let fileUrl = file.url;
      window.open(fileUrl, '_blank');
    },
    handleChangeBoomGy(file, files, boom) {
      boom.gy_fileList = files;
      this.curBoom = boom;
    },
    handleSuccessBommGy(res, file, files, boom) {
      if (res.code!=0) {
        this.$message.error(res.message);
        files.indexOf(file) > -1 && files.splice(files.indexOf(file), 1);
        boom.gy_fileList = files;
        return
      }
      boom.gy_fileList = files;
      this.updateBoomMsg();
    },
    handleError(error, file, fileList) {
      this.$message.error('上传失败,请稍后重试');
    },
    removeBoomGy(file, files, boom) {
      boom.gy_fileList = files;
      this.curBoom = boom;
      this.updateBoomMsg();
    },
    beforeUploadGy(file) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("上传图片大小不能超过 10MB!");
      }
      return isLt2M;
    },
    beforeRemoveGy(file, fileList) {
      return this.$confirm(`确定删除该附件`);
    },

问题点:

文件上传,httpcode码200,但是接口内业务码报错

正常报错,例如状态码:400,500之类的,好像 on-error 会触发
如果状态码是200,报错是由业务码来判断,就有点麻烦。
在这里插入图片描述
接口报错,但是组件却显示正常上传。

这时,我们就需要去处理 on-success 方法。如果是报错,则需要将当前这个文件去掉。

handleSuccess(res, file, files, boom) {
  //接口报错
  if (res.code!=0) {
      this.$message.error(res.message);
      //files 内找到对应的文件,然后删掉
      files.indexOf(file) > -1 && files.splice(files.indexOf(file), 1);
      boom.gy_fileList = files;
      return
    }
    boom.gy_fileList = files;
    this.updateBoomMsg();
  },

总结:
vue操作的数据,请记住,数据是关键。接口报错,直接删除异常数据即可。我在这上面纠结了好久,经过多次测试,发现数据有异常,files 这个是所有文件数据,错误的也在理,直接删除即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值