vue 中当提交表单时里面需要上传照片时,需要使用到formData将对象转换成表单数据
<el-upload
class="upload-demo"
ref="upload"
action
accept=".jpg .png"
:on-change="handleChange"
:on-remove="handleRemove"
:file-list="fileList"
:auto-upload="false">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
</el-upload>
使用vue中upload组件,详细请看vue文档
data(){
return{
ruleForm:{
user{
name:'',
sex:'',
phone:''
}
},
fireList:[]
}
},
methods:{
handleChange(file,fileList){
this.ruleForm.fileList = fileList
this.fileList = fileList
}
}
验证表单之后,将对象转换成表单数据
let form_data = new formData()
//将不为空的表单数据添加到formData中
let params = this.ruleForm.user
for (let key in params){
//判断是否为空
if(params[key]!="" || params[key]!=null || params[key]!=undefined){
form_data.append(key,params[key])
}
}
if(this.ruleForm.fileList.length > 0){
for(let i = 0;i<this.ruleForm.fileList.length;i++){
form_data.append(`files`,this.ruleForm.fileList[i].row)
}
}
最后将form_data传至后台