业务需求
- 填写表单字段
- 手动选择文件
- 点击保存上传文件并保存表单
思路
- 校验表单
- 校验已选择文件
- 触发 el-upload 文件上传函数
- 每个文件做一次格式转换(如果格式一致可忽略)
- 判断所有文件的状态是否都是成功状态
- 所有文件上传成功才调用接口
<el-form ref="form" :model="form">
<el-form-item>
<el-input>
</el-form-item>
<el-upload
:action="upload.actionUrl"
:file-list="fileList"
:on-success="handleUploadSuccess"
:on-change="handleChange"
:show-file-list="true"
:headers="upload.headers"
class="upload-file-uploader"
ref="upload"
:auto-upload="false"
>
<el-button size="mini" type="primary">选取文件</el-button>
</el-upload>
<el-button @click="onSave">保存</el-button>
</el-form>
<script>
export default {
data() {
return {
upload: {
actionUrl: 'http://xxx.com/common/upload',
headers: {
Authorization: 'Bear xxx',
}
}
fileList: [],
form: {
dbFileList: [],
},
}
},
methods: {
onSave() {
this.$refs['form'].validate(valid => {
if(!valid) {
return
}
if(this.fileList.length === 0) {
this.$message.warn('请上传文件')
return
}
this.$refs.upload.submit()
})
}
handleChange(file, fileList) {
this.fileList = fileList
},
handleRemove(file, fileList) {
this.fileList = fileList
}
handleUploadSuccess(file, fileList) {
this.form.dbFileList.push({
dbFileName: file.name,
dbFileUrl: file.response.url
})
let allSuccess = fileList.every(file =>
file.status === 'success')
if(allSuccess) {
handleSave()
}
},
async handleSave() {
await doSave(this.form)
this.$message.success('保存成功')
}
}
}
</script>
参考链接
el-upload 组件手动上传官方文档