【vue】element ui - el-upload 上传校验文件,格式和大小

el-upload 上传校验文件,格式和大小

下面例子的情况是一个上传按钮,点击直接弹出选择文件


    文档上传
  

属性解释
actionurl 上传接口地址
on-change 选择文件,上传文件成功或上传文件失败时调用
show-file-list=“false” 隐藏文件列表
on-success 上传成功后调用
before-upload 上传前调用
accept接收文件格式,在选择上传文件时进行限制,如图:
【vue】element ui - el-upload 上传校验文件,格式和大小_第1张图片

v-loading.fullscreen.lock=“fullscreenLoading” 全屏loading

相关方法

beforeFileUpload(file) {
      this.fullscreenLoading = true;
      //校验文件大小
      if (file.size >= 10485760) {
        this.$message({
          type: "error",
          message: "文件大小超出10M,请重新上传!",
        });
        this.fullscreenLoading = false;
        return;
      }
	//校验文件格式
      if (
		//excel
        file.type !==
          "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" &&
		//excel
        file.type !== "application/vnd.ms-excel" &&
		//word
        file.type !== "application/msword" &&
		//pdf
        file.type !== "application/pdf" &&
		//word
        file.type !==
          "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
      ) {
        this.$message({
          type: "warning",
          message: "附件格式错误,请删除后重新上传!",
        });
        return;
      }
    },

handleChange(file, fileList) {
      this.fileTemp = file.raw;
      if (!this.fileTemp) {
        this.$message({
          type: "warning",
          message: "请上传附件!",
        });
      }
    },
    handleRemove(file, fileList) {
      this.fileTemp = null;
    },
    uploadSuccess(res, file) {
      setTimeout(() => {
        this.fullscreenLoading = false;
      }, 1000);
      this.fileTemp = file.raw;
      //获取文件大小
      let docSize = this.fileTemp.size;
      //获取文件名字
      let docName = res.data.name.substring(0, res.data.name.lastIndexOf("."));
      //获取文件格式
      let docFormat = res.data.name.substring(
        res.data.name.lastIndexOf(".") + 1
      );
      //获取文件路径
      let docPath = res.data.url;
      //成功后跳转
      this.$router.push({
        name: this.targetpage,
        params: {
          docName: docName,
          docPath: docPath,
          docFormat: docFormat,
          docSize: docSize,
        },
      });
    },

你可能感兴趣的:(vue开发实践总结,vue.js,ui,elementui)