el-upload使用formData上传文件

需求背景:点击输入框选择要上传的压缩包文件,算中后输入框显示选择的文件名称

<el-upload
                  ref="uploadFile2"
                  action="string"
                  :limit="1"
                  accept=".zip"
                  :on-change="handleChange"
                  :auto-upload="false"
                  :file-list="fileList"
                  :show-file-list="false"
                >
                  <el-input v-model="ruleForm.agentFile"></el-input>
                </el-upload>

这里绑定on-change方法目的就是拿变量接收前端上传的文件以及要显示的文件名称;

    // 上传的文件发生变化时
    handleChange(file, fileLists) {
      this.ruleForm.agentFile = file.name;
      fileObj = file.raw;
      console.log(file);
      // 这里把数组置空是为了每次只能上传一个文件,以防报错
      this.fileList = [];
    },

 接下来是表单提交

// 表单提交
    submitForm() {
      // 验证表单是否填写完整且正确
      this.$refs["ruleForm"].validate(valid => {
        if (valid) {
          let formData = new FormData();
          // 把新增时后端要求的参数都添加进来
          formData.append("agentName", this.ruleForm.agentName);
          formData.append("agentRole", this.ruleForm.agentRole);
          formData.append("agentType", this.ruleForm.agentType);
          formData.append("description", this.ruleForm.description);
          formData.append("unit", this.ruleForm.unit);
          formData.append("agentFile", fileObj);
          // 这里使用formData类型是因为要传给后端文件
          addAgent(formData).then(data => {
            if (data.code == 200) {
              this.$modal.msgSuccess(data.msg);
              this.dialogVisible = false;
              this.$emit("refreshList");
              // 把表单信息清空,保证下次打开的时候是全新空白的
              this.reset();
              // 把表单校验信息清空
              this.$refs["ruleForm"].clearValidate();
            } else {
              this.$modal.msgError(data.msg);
            }
          });
        }
      });
    }

之前都是上传文件单独要个接口,这样的话新增和上传文件只需要一个接口,又学到了~

猜你喜欢

转载自blog.csdn.net/song_song0927/article/details/130684471