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

以前は、ファイルのアップロードには別のインターフェイスが必要だったので、ファイルの追加とアップロードに必要なインターフェイスは 1 つだけで、改めて学びました~

おすすめ

転載: blog.csdn.net/song_song0927/article/details/130684471