用formData实现表单提交和文件上传

    <el-form-item
      prop="uploadFile"
      label="上传文件">
      <el-upload
        ref="fileUpload"
        :auto-upload="false"
        :limit="3"
        :on-change="fileOnChange"
        :before-upload="fileBeforeUpload"
        :before-remove="fileBeforeRemove"
        size="mini"
        class="upload-file"
        action=""
        multiple>
        <el-button
          class="upload-button"
          size="small"
          type="primary">请选择文件</el-button>
          <!--<div
          slot="tip"
          class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>-->
      </el-upload>
    </el-form-item>
    <el-form-item
      prop="uploadImg"
      label="上传图片">
      <!--:on-remove="imgRemoveList"-->
      <el-upload
        ref="imgUpload"
        :auto-upload="false"
        :limit="3"
        :on-change="imgOnChange"
        :before-upload="imgBeforeUpload"
        :before-remove="imgBeforeRemove"
        size="mini"
        class="upload-img"
        action=""
        accept=".jpg,.jpeg,.png"
        list-type="picture-card"
        multiple>
        <!--<i class="el-icon-plus"/>-->
        <i class="icon-tupian"/>
        <!--<div class="el-upload__text">将文件拖到此处</div>-->
        <div
          slot="tip"
          class="el-upload__tip">只能上传jpg/png文件,大小不超过20M</div>
      </el-upload>
    </el-form-item>

on-change:文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
before-upload:上传文件之前的钩子,参数为上传的文件,若返回 false 或者返回 Promise 且被 reject,则停止上传。
before-remove:删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除。

  data() {
    let validateLicense = (rule, value, callback) => {
      if (!(this.imgSizeIsSatisfy.length === 0)) {
        callback(new Error('上传图片大小不能超过 5MB!'));
      } else {
        callback();
      }
    };
    let fileValidate = (rule, value, callback) => {
      if (!(this.fileSizeIsSatisfy.length === 0)) {
        callback(new Error('上传图片大小不能超过 10MB!'));
      } else {
        callback();
      }
    };
    return {
      dealForm: {
        solutions: '',
        dealStatus: '',
        dealFunction: ''
      },
      dealFormRules: {
        uploadImg: [{ validator: validateLicense }],
        uploadFile: [{ validator: fileValidate }]
      },
      uploadFile: [],
      uploadImg: [],
      imgSizeIsSatisfy: [],
      fileSizeIsSatisfy: []
    };
  },
  methods: {
    imgBeforeUpload(file) {
      this.uploadImg.push(file);
      return false;
      // 返回false,停止上传
    },
    fileBeforeUpload(file) {
      this.uploadFile.push(file);
      return false;
    },
    saveDealEvent() {
      this.$refs.dealForm.validate(valid => {
        if (valid) {
          this.$confirm('确认提交吗?', '提示', {})
            .then(() => {
              // 创建一个formData对象
              const formData = new FormData();
              // 把表单双向绑定的数据添加到formData对象里面
              Object.keys(this.dealForm).forEach(key => {
                formData.append(key, this.dealForm[key]);
              });
              // 添加eventId到formData对象里面
              formData.append('eventId', this.evtId);
              // 手动上传文件列表
              this.$refs.fileUpload.submit();
              this.$refs.imgUpload.submit();
              // 把要上传的文件添加到formData对象里面
              for (let i = 0; i < this.uploadFile.length; i++) {
                formData.append('fileFiles', this.uploadFile[i]);
              }
              for (let i = 0; i < this.uploadImg.length; i++) {
                formData.append('imgFiles', this.uploadImg[i]);
              }
              // 提交表单
              saveDealEvent(formData).then(res => {
                // 提交后置空
                this.dealForm = {};
                this.uploadFile = [];
                this.uploadImg = [];
                this.$refs['dealForm'].resetFields();
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
              });
            })
            .catch(e => {
              console.log(e);
            });
        }
      });
    },
    imgOnChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 5;
      if (!isLt2M) {
        this.imgSizeIsSatisfy.push(file.name);
        this.$refs.dealForm.validateField('uploadImg');
      }
    },
    imgBeforeRemove(file) {
      if (!(this.imgSizeIsSatisfy.indexOf(file.name) === -1)) {
        let temp = this.imgSizeIsSatisfy.indexOf(file.name);
        this.imgSizeIsSatisfy.splice(temp, 1);
        this.$refs.dealForm.validateField('uploadImg');
      }
    },
    fileOnChange(file, fileList) {
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.fileSizeIsSatisfy.push(file.name);
        this.$refs.dealForm.validateField('uploadFile');
      }
    },
    fileBeforeRemove(file) {
      if (!(this.fileSizeIsSatisfy.indexOf(file.name) === -1)) {
        let temp = this.fileSizeIsSatisfy.indexOf(file.name);
        this.fileSizeIsSatisfy.splice(temp, 1);
        this.$refs.dealForm.validateField('uploadFile');
      }
    }
  }

请求方式:post的body参数
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐