el-upload 切片上传jar包并添加form表单校验


      
        
          
            选择文件
            开始上传
          
          
        
        
          
        
        
          
        
      
      
    


      // 上传列表
      fileList: [],
      percentage: 0,
      // 上传loading状态
      accept: ".jar",
      ruleForm: {
        FuncClass: null,
        FuncName: null,
        jarName: null, // 包名称
      },

      rules: {
        FuncName: [
          { required: true, message: "请输入函数名", trigger: "change" },
        ],
        FuncClass: [
          {
            required: true,
            message: "请输入Function Class",
            trigger: "change",
          },
        ],
        jarName: [{ required: true, message: "请上传jar包", trigger: "change" }],
      },

    /** 上传前 */
    beforeUpload(file) {
      // 限制文件类型
      const suffix = fileSuffix(file.name);
      if (suffix.toLowerCase() !== "jar") {
        this.$notification.warning(`文件格式错误,请选择jar文件!`);
        return false;
      }
      // 限制文件大小
      const maxSize = 1024 * 1024 * 300; // 300MB
      if (file.size > maxSize) {
        this.$notification.warning("文件大小不能超过300MB!");
        return false;
      }
      return true;
    },
    /** 删除jar包 */
    async deleteJar(jarType, file) {
      const params = {};
      const res = await 接口(params);
      if (res.data.success) {
        this.$notification.success("删除成功!");
        return true;
      } else {
        this.$notification.error(res.data.errorMsg);
        return false;
      }
    },
    /** 删除主包 */
    async handleRemove(file, fileList) {
      const state = await this.deleteJar("main", file);
      if (state) {
        this.ruleForm.jarName = "";
        this.percentage = 0;
        this.$refs.upload.clearFiles();
        this.cancelTokenSource.cancel("取消上传");
      } else {
        this.fileList = fileList;
        return Promise.reject();
      }
    },
    /** 主包自定义上传 */
    uploadChunk(info) {
      this.uploadLoading = true;
      const { file } = info;
      const prom = new Promise((resolve, reject) => {
        const chunkSize = 10 * 1024 * 1024; // 每片10mb
        const chunksTotal = Math.ceil(file.size / chunkSize); // 分片总数
        const uploadNextChunk = async (chunkIndex) => {
          const start = chunkIndex * chunkSize;
          const end = Math.min(start + chunkSize, file.size);
          const chunk = file.slice(start, end); // 获取当前分片的数据
          const formData = new FormData();
          formData.append(
            "param",
            JSON.stringify({
              jobType: "spark",
              taskCode: this.taskCode,
              jarType: "main",
              jarName: file.name,
              index: chunkIndex,
              totalSize: file.size,
              burstSize: chunksTotal,
            })
          );
          formData.append("file", chunk);
          this.cancelTokenSource = axios.CancelToken.source();
          const result = await axios.post(this.actionPath, formData, {
            onUploadProgress: (progressEvent) => {
              if (progressEvent.loaded / progressEvent.total === 1) {
                this.percentage = Math.round((chunkIndex / chunksTotal) * 100);
              }
            },
            cancelToken: this.cancelTokenSource.token,
          });
          console.log(result, "主包");
          if (result.data.success) {
            // this.percentage = Math.ceil(chunkIndex / chunksTotal * 100)
            // 处理分片上传成功的逻辑
            if (chunkIndex === chunksTotal - 1) {
              this.percentage = 100;
              this.ruleForm.jarName = file.name;
              this.$refs["ruleForm"].validateField("jarName", () => {}); // 重新校验
              this.$notification.success(`${file.name}上传成功!`);
              this.uploadLoading = false;
              resolve(); // 上传完成
            } else {
              uploadNextChunk(chunkIndex + 1); // 继续上传下一个分片
            }
          } else {
            this.percentage = 0;
            this.ruleForm.jarName = "";
            this.fileList = [];
            this.$notification.error(`${file.name}上传失败!`);
            this.uploadLoading = false;
            reject();
          }
        };
        uploadNextChunk(0); // 开始上传第一个分片
      });
      prom.abort = () => {
        console.log(`${file.name}停止上传!`);
        this.percentage = 0;
        this.uploadLoading = false;
      };
      return prom;
    },
     /** 主类包change */
    async handelChange(file, fileList) {
      console.log(file, fileList, "chang");
      // 选文件前校验
      const state = this.beforeUpload(file);
      if (!state) {
        this.fileList = [];
        return false;
      }
      this.fileList = fileList;
    },
    startUpload() {
      this.$refs.upload.submit();
    },
    submitBtn() {
      this.$refs["ruleForm"].validate((valid) => {
        if (valid) {
          this.$parent.flinkLoading = true;
          
          const params = {};
          接口(params)
            .then((res) => {
              if (res.data.success) {
                this.$notification.success("提交成功");
              } else {
                this.$notification.error(res.data.errorMsg);
              }
            })
            .finally(() => {
              this.$parent.flinkLoading = false;
            });
        } else {
          return false;
        }
      });
    },

    setTaskReview(model) {
        // 回显
        let reviewModel = JSON.parse(model.script);
        const { dependencyNames, mainClassName, jarName, userParameters } =
          reviewModel;
        this.ruleForm.jarName = jarName ?? '';
        this.ruleForm.mainClassName = mainClassName ?? '';
        this.ruleForm.userParameters = userParameters ?? '';
        this.ruleForm.dependencyNames = dependencyNames ?? '';
        if (jarName) {
          this.fileList = [
            {
              name: jarName,
              url: "",
            },
          ];
        } else {
          this.fileList = []
        }
        
    },
/**
 * 获取文件名后缀
 * @param {String} name
 * @return {String} 
 */
function fileSuffix(name) {
    const dotIndex = name.lastIndexOf('.');
    const extension = name.substring(dotIndex + 1);
    return extension
}

你可能感兴趣的:(jar,vue.js,elementui)