在应用elementUI进行文件提交的时候,有时候须要提交一些别的参数,这时候须要接管到上传的文件之后,将文件转为formData表单数据(具体看后端)再进行提交。
首先咱们须要再模板中先配置下 el-upload,将 auto-upload 设置为 false 禁止主动提交,相干的属性能够查看elementUI文档:
<el-upload name="file" ref="upload" :show-file-list="false" :action="baseUrl + '/pc/fee/bill/take-excel'" :before-upload="beforeUpload" :on-change="addFile" :file-list="fileList" :auto-upload="false"> <el-button type="primary" size="small">抉择文件</el-button></el-upload>
而后就是在用户将文件抉择好上传的时候,咱们须要转成 FormData 的格局能够先应用
let formdata = new FormData()
创立进去,而后通过提供的
formdata.append('name', value)
办法向formdata外面增加键值对。须要留神的是,这个时候如果想要查看是否增加胜利千万不要用 console.log() 间接打印的形式,这样你会发现输入的是空的,正确的形式是通过给定的 get/getAll keys等形式获取到数据:
console.log(formdata) //会输入一个空的 FormDataconsole.log(formdata.get('name')) //会输入对应的value
这样就能输入你的 formdata 数据啦。
筹备工作实现之后,和后端小伙伴沟通下,咱们来配置下申请的接口:
billChargePostApiQuery(url,data){ return request({ url: url, headers: { "Content-Type": "multipart/form-data" //留神格局 }, method: 'post', data, baseURL: process.env.NODE_ENV === 'production' ? '正式' : '测试' }) },
而后将接口所须要的一些参数也加进 formdata 中:
let data ={ schoolId: this.$store.state.user.school_id, schoolName: this.$store.state.user.school_name, classificationId: this.form.order_sort, classificationName: sort_name, type: this.checkList.join(','), feeType: this.form.month? '2': '1', schoolYear: schoolYearGet, semester: this.form.semester, payMonth: this.form.month, createUserId: this.$store.state.user.userinfo.memberId, createUserName: this.$store.state.user.userinfo.name}//应要求转为 json 字符串增加进去this.fileData.append("takeExcelQuery", JSON.stringify(data))this.$API.billChargePostApi('pc/fee/bill/take-excel',this.fileData).then(res => { console.log('提交胜利',res);}).catch(err => { console.log('提交失败', err);})
剩下的就是后端小伙伴的工作啦。
欢送斧正!