其他分享
首页 > 其他分享> > 【vue】element ui - el-upload 上传校验文件,格式和大小

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

作者:互联网

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

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

<el-upload
    ref="upload"
    class="zls-upload-demo"
    :action="actionurl"
    :on-change="handleChange"
    :show-file-list="false"
    :file-list="fileListUpload"
    :on-success="uploadSuccess"
    :before-upload="beforeFileUpload"
    accept=".pdf,.docx,.doc,.xls,.xlsx,.ceb"
  >
    <el-button
      type="primary"
      v-loading.fullscreen.lock="fullscreenLoading"
      >文档上传</el-button
    >
  </el-upload>

<el-upload>属性解释
actionurl 上传接口地址
on-change 选择文件,上传文件成功或上传文件失败时调用
show-file-list=“false” 隐藏文件列表
on-success 上传成功后调用
before-upload 上传前调用
accept接收文件格式,在选择上传文件时进行限制,如图:
请添加图片描述

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,
        },
      });
    },

标签:el,vue,name,type,校验文件,file,res,message,上传
来源: https://blog.csdn.net/loyd3/article/details/122280145