用elementui的upload上传文件,只能上传一个文件,并最后和表单一起提交

44 阅读1分钟

html

      <el-form ref="form" :model="uploadForm" label-width="80px" v-show="showUpload">
        <el-form-item label="文件">
          <el-upload action :auto-upload="false" :on-change="onChangeFile" ref="upload">
            <el-button size="small" type="primary">选择文件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="uploadForm.remark"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="uploadFile">上传</el-button>
        </el-form-item>
      </el-form>

js

data() {
    return {
      uploadForm: {
        remark: ''
      },
      file: null,
    }
}
methods: {
    onChangeFile(file, fileList) {
      // console.log('onChangeFile', file, fileList)
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
      this.file = file
    },
    uploadFile() {
      const form = new FormData();
      // console.log('uploadFile',this.file, this.file.raw)
      form.append("file", this.file.raw);
      form.append('id', this.uploadForm.id)
      form.append('remark', this.uploadForm.remark)
      uploadFile(form).then(response => {
        // console.log('uploadFile', response)
        this.$modal.msgSuccess("上传成功");
        this.$refs.upload.clearFiles() //清空上传列表
        this.file = null
        this.uploadForm.remark = ''
      }).catch(
        this.$refs.upload.clearFiles(),
        this.file = null,
        this.uploadForm.remark = ''
      );
    },
}

image.png