1. 程式人生 > 其它 >Ant Design Vue 實現檔案上傳 (通過點選提交按鈕後開始上傳)

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>