上传文件并显示上传进度条

https://www.cnblogs.com/shizqiang/p/5984783.html

https://www.jb51.net/article/147092.htm

  getProgress(event) {
      event = event || window.event;
      this.percentage = Math.floor(100 * (event.loaded / event.total));
      this.uploadObject.loaded = formatSize(0, event.loaded, 2);
      this.uploadObject.total = formatSize(0, event.total, 2);
      this.uploadObject.setSpeed(event.loaded);
    },

    getUploadXhrObject() {
      if (this.xhrObject == null) {
        const xhr = $.ajaxSettings.xhr();
        xhr.upload.addEventListener("progress", this.getProgress, false);
        this.xhrObject = xhr;
      }
      return this.xhrObject;
    },

    softwarePackFileChange() {
      const fileTypes = "jar,war";
      const fileTypeArray = fileTypes.split(",");

      const softwarePackFile = $("#softwarePackFile").get(0).files[0];
      const filePathArray = softwarePackFile.name.toLowerCase().split('.');
      const fileType = filePathArray[filePathArray.length - 1];
      if (_.indexOf(fileTypeArray, fileType) == -1) {
        $WarnMessage(`支持的附件格式【${fileTypes}】,当前格式:${fileType}。`);
        return;
      }

      const formData = new window.FormData();
      formData.append("file", softwarePackFile);
      formData.append("versionId", this.versionId);
      formData.append("shelfId", this.shelfId);
      this.uploadState = 1;
      this.uploadStateText = "上传中";
      this.clearCloseTimer();

      $.ajax({
        type: "POST",
        data: formData,
        contentType: false,
        processData: false,
        xhr: this.getUploadXhrObject,
        url: `${$$apiDevOpsPath}/uploadAppPkg`,
        beforeSend: request => {
          this.uploadObject = new Upload();
        },
        success: response => {
          const message = response.message;
          if (message != undefined) {
            $WarnMessage(message);
            this.uploadStateText = "上传失败";
            this.progressType = "exception";
          } else {
            const shelfVersionAppPkg = response.model;
            shelfVersionAppPkg.minioHost = response.host;
            this.uploadStateText = "上传成功";
            this.progressType = "success";
            this.$emit("pushAppSoftwarePackage", shelfVersionAppPkg);

            this.closeTimer = setTimeout(() => {
              this.uploadState = 3;
              this.clearCloseTimer();
            }, 3000);
          }
        },
      });
    },

    clearCloseTimer() {
      if (this.closeTimer != null) {
        clearTimeout(this.closeTimer);
        this.closeTimer = null;
      }
    },

 

posted @ 2020-06-09 18:46  氧化成风  阅读(1106)  评论(0编辑  收藏  举报