vue el-upload form 同时提交

项目需要form 表单和文件上传同时在一个请求,废话不多说上代码:

上传的组件使用pug格式

.row.my-4
.col-12
el-form(:model='domain', :rules='validateRules', v-loading='loading', ref='form', label-width='120px')
el-form-item(label="请选择服务分类",prop="options")
el-cascader(:options="options",v-model="domain.selectedOptions" ,style="width:80%")
el-form-item(label='服务名称:', prop='name')
el-input(v-model='domain.name', style='width: 80%')
el-form-item(label='服务价格:', prop='name')
el-input(v-model='domain.price', style='width: 80%')
el-upload.upload-demo(ref='upload', :before-upload="uploadform" :on-preview='handlePreview', :on-remove='handleRemove', :file-list='fileList', :auto-upload='false')
el-button(slot='trigger', size='small', type='primary') 选取文件
// el-button(style='margin-left: 10px;', size='small', type='success', @click='submitUpload') 上传到服务器
.el-upload__tip(slot='tip') 只能上传jpg/png文件,且不超过500kb


.row
.col-12.mb-4.text-center
el-button(size='middle', @click='handleBack(domain.id)') 返回
el-button(type='primary', @click='onClickSave()') 确定

vue method处理

  uploadform: function(file) {
        const formData = new FormData()
        // console.log(this.domain)
        delete this.domain.id
        Object.keys(this.domain).forEach(key => {
          formData.append(key, this.domain[key])
        })
        formData.append('file', file)
       
        this.$refs.form.validate((valid) => {
          if (!valid) {
            return
          }
          const api = this.domain.id ? API.service.update : API.service.create
          const id = this.domain.id
          if (!this.domain.id) {
            this.domain.id = id
          }
          this.domain.contactor = null
          // console.log(this.service)
          api(formData).then((res) => {
            const data = res.data
            console.log('service saved: ' + JSON.stringify(data))
            const path = '/services'
            if (this.domain.id !== undefined) {
              this.$router.push({
                path: '/services/' + this.domain.id
              })
            } else {
              this.$router.push({
                path: path
              })
            }
          }).catch(() => {
            this.$message.error('保存失败,请稍后重试')
          })
        })
      },
      onClickSave: function() {
        this.$refs.upload.submit()
      }

 注意,红色的地方对应

后台实现


public Result add(@ModelAttribute Object object)

 

至此实现完成

欢迎学习

 

posted @ 2018-09-05 23:48  菜鸟的进击  阅读(9161)  评论(0编辑  收藏  举报