項目須要form 表單和文件上傳同時在一個請求,廢話很少說上代碼:javascript
上傳的組件使用pug格式vue
.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處理java
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()
}
注意,紅色的地方對應api
後臺實現服務器
public Result add(@ModelAttribute Object object)
至此實現完成
歡迎學習app