element 中上传文件和表单提交公用一个接口

在项目中需要使用文件上传,和表单内容同时提交的情况

1.使用element中Upload 上传组件,除了上传文件还需要同时提交其他数据,可以进行手动上传
但是upload组件中上传的地址action必选参数,不能删除,此时将action="#"即可。
:auto-upload="false"即设置为手动上传

  <el-form-item label="文件上传:" prop="uploadFile">
        <el-upload
          class="upload-demo"
          action="#"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :on-change="uploadChange"
          multiple
          :limit="1"
          :on-exceed="handleExceed"
          :file-list="fileList"
          :auto-upload="false"
        >
          <el-button size="small" type="primary">点击上传</el-button>
          &nbsp;<span slot="tip" class="el-upload__tip">
            只能上传1个文件
          </span>
        </el-upload>
      </el-form-item>

2.手动上传时候,文件取值为filelist列表中每一项的raw,用formdata上传文件,file:(binary)

 uploadChange(file, fileList) {
      this.form.file = fileList[0].raw;
    }

3.表单提交

    onSubmit(formName) {
      let formData = new FormData();
      formData.append("file", this.form.file);
      formData.append("username", this.form.username);
      formData.append("appid", this.form.appid);
      formData.append("appName", this.form.appName);
      formData.append("groupId", this.form.groupId);
      formData.append("uploadPipe", this.form.uploadPipe);
      formData.append("fileUrl", this.form.fileUrl);
      formData.append("groupName", this.form.groupName);
      let config = {
        headers: {
          "Content-Type": "multipart/form-data"
        }
      };
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.$axios
            .post(this.$apiUrl.fileUpload, formData, config)
            .then(res => {
              if (res.status == "200") {
                this.$message({
                  message: "提交成功",
                  type: "success"
                });
                this.$router.push("/");
              }
            });
        } else {
          return false;
        }
      });
    },
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容