Ant Design Vue 实现文件上传 (通过点击提交按钮后开始上传)

 

 

<template>
  <div style="max-width: 890px">
      <a-form-model ref="ruleForm" :rules="rules" :model="form" :label-col="labelCol" :wrapper-col="wrapperCol">
        <a-form-model-item label="名称" prop="name" has-feedback>
          <a-input v-model="form.name" />
        </a-form-model-item>
        <a-form-model-item label="描述" prop="desc" has-feedback>
          <a-input type="textarea" v-model="form.desc" />
        </a-form-model-item>
        <a-form-model-item label="文件选择">
          <a-upload :before-upload="beforeUpload" :remove="handleRemove" :multiple="false" :file-list="fileList">
           <a-button>
             <a-icon type="upload" /> Select File
           </a-button>
         </a-upload>
      </a-form-model-item>
        <a-form-model-item :wrapper-col="{ span: 14, offset: 4 }">
          <a-button type="primary" @click="onSubmit">提交</a-button>
          <a-button style="margin-left: 10px;" @click="resetForm">重填</a-button>
      </a-form-model-item>
      </a-form-model>
  </div>
</template>>

<script>

export default {
  data () {
    return {
      labelCol: { span: 4 },
      wrapperCol: { span: 14 },
      fileList: [],
      uploading: false,
      form: {
        from: '',
        desc: ''
      },
      rules: {
        name: [{ required: true, message: 'Please select name!' }],
        desc: [{ required: true, message: 'Please select name!' }],
      }
    }
  },
  methods: {
    // 文件移除
    handleRemove (file) {
      const index = this.fileList.indexOf(file)
      const newFileList = this.fileList.slice()
      newFileList.splice(index, 1)
      this.fileList = newFileList
    },
    beforeUpload (file) {
      this.fileList = [...this.fileList, file]
      return false
    },
    // 上传文件点击确认
    onSubmit () {
      this.$refs.ruleForm.validate(async valid => {
        if (valid) {
          const { fileList } = this

          const formData = new FormData()
          fileList.forEach((file) => {
            formData.append('file', file)
          })

          for (const prop in this.form) {
            if (Object.prototype.hasOwnProperty.call(this.form, prop)) {
              formData.append(prop, this.form[prop])
            }
          }
          this.uploading = true

          const res = await FileUpload(formData)
          if (res.code === 200) {
            this.fileList = []
            this.uploading = false
            this.$msgsuccess(res.msg)
            this.$router.push({ name: 'FileList' })
            // this.$emit('getPath',)
          } else {
            this.uploading = false
            this.$msgerror(res.msg)
          }
        } else {
          return false
        }
      })
    },
    // 重置表单
    resetForm () {
      this.$refs.ruleForm.resetFields()
    }
  }
}
</script>

<style lang="sass" scoped>
</style>

 

上一篇:如何实现 的虚拟dom


下一篇:ES6中的Proxy