vue+element实现文件上传功能及相关优化


前言

注:文章记录了vue+element上传功能的实现,和有关规范上传文件类型及上传进度的优化。 其中有关element上传组件的各种属性及相关函数详细讲解可见官方文档

Element Upload上传组件官方文档

引入element上传组件

<!-- action用于填写后端接收文件的接口 -->
<el-upload
  :limit="1"
  action="http://xxx.xx.xx//xxx"
  :file-list="fileList"
  :before-upload="beforeAvatarUpload"
  :on-remove="handleRemove"
  :on-success="handleSuccess"
  :on-error="handleError"
  :auto-upload="true"
  :on-progress="onProgressTest"
  name="upfile"
  class="videoUpButton"
>
  <el-button slot="trigger" size="small" type="primary"
    >选取上传视频</el-button
  >
</el-upload>

上传组件部分属性对应的函数说明

参数说明
before-upload上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传
on-remove文件列表移除文件时的钩子
on-success文件上传成功时的钩子
on-error文件上传失败时的钩子
on-progress文件上传时的钩子

配置上传组件对应生命钩子的功能函数

<script>
export default {
  name: "video-content",
  data() {
    return {
      fileList: [],
    };
  },
  methods: {
    //上传功能对应的生命钩子函数
    //"before-upload" 中规范上传文件的格式类型,此处已上传视频为例子
    beforeAvatarUpload(file) {
      const isMP4 = file.type === "video/mp4";
      const isFLV = file.type === "video/flv";
      const isF4V = file.type === "video/f4v";
      const isWEBM = file.type === "video/webm";
      if (!isMP4 && !isFLV && !isF4V && !isWEBM) {
        this.$message.error("只能上传 mp4/flv/f4v/webm 格式!");
      }
      return isMP4 || isFLV || isF4V || isWEBM;
    },
    handleRemove(file, fileList) {
    },
    handleSuccess(response, file, fileList) {
    },
    handleError(err, file, fileList) {
    },
    //一般情况下配置的上传组件上传到达100%时会有短暂的卡顿(因为此时后端收到文件需要做相应处理,然后才返回告诉前端,达到上传成功),若此时用户以为已经上传成功做了如:刷新页面、退出页面等操作,则会导致文件上传失败
    //故在"on-progress" 设置文件上传始终停留在99%直至上传成功变成√
    onProgressTest(event, file, fileList) {
      let index = 0;
      // 只有fileList 跟file 里面的uid是唯一互相对应的
      fileList.forEach((v, i) => {
        if (v.uid === file.uid) {
          index = i;
        }
      });
      // 获取进度条进度
      let percent = parseInt(event.percent);
      this.$nextTick(() => {
        setTimeout(() => {
          if (percent >= 99) {
            // 当动态的进度 >=99 就获取dom,让值一直显示99直到上传成功
            let dom = document.getElementsByClassName("el-upload-list__item")[
              index
            ];
            let progressText = dom.getElementsByClassName("el-progress__text");
            if (progressText && progressText.length) {
              progressText[0].style.opacity = 0;
              progressText[0].innerText = "99%";
              progressText[0].style.opacity = 1;
            }
          }
        });
      });
    },
  },
};
</script>


提示:文章到此结束,若有不足还请各位指出。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值