Antd upload组件结合form上传文件及其他参数总结
前端:
form表单中:
<a-form :form="form" @submit="handleSubmit">
<a-form-item
style="text-align: center"
:label="$t('form.basic-form.title.photo')"
:labelCol="{lg: {span: 7}, sm: {span: 7}}"
:wrapperCol="{lg: {span: 10}, sm: {span: 17} }"
>
<Myupload @child-event="getPhotosFromChild" v-decorator="['file',{rules: [{required: true, message: '请务必上传至少一张图片'}]}]" ref="myupload"/>
</a-form-item>
</a-form>
Myupload中:
<a-upload :headers="headers" :file-list="fileList" :remove="handleRemove" :before-upload="beforeUpload">
<a-button> <a-icon type="upload" />上传图片</a-button>
</a-upload>
思路:图片上传至 Myupload 组件,Myupload 组件触发 beforeUpload 方法,将 fileList[](data中的)传给父组件 a-form-item
beforeUpload(file) {
this.fileList = [...this.fileList, file]
this.$emit('child-event',this.fileList)
return false
},
回到 form 表单组件,收到子组件发来的 fileList (这里只上传一个图片),将其添加进 formData 中,此处 formData:
data () {
return {
form: this.$form.createForm(this),
formData: new FormData()
}
},
收到子组件传来的 fileList 后的回调
getPhotosFromChild(data) {
this.formData.append('file',data[0])
console.log('asdasd@@@file',this.formData.get('file'))
},
这里其他参数最终也会被 append 到 FormData 对象中,因为我的后端要接受的是 multipart/form-data 类型参数,而不是 application/json ,全都封装成 FormData 后,浏览器会直接将数据识别为 multipart/form-data 类型并发送给后端
后端:
直接接收一个 HttpServletRequest request
对象进行处理,获取前端的数据:
MultipartHttpServletRequest params = (MultipartHttpServletRequest) request;
MultipartFile file = ((MultipartHttpServletRequest) request).getFile("file");
String goodsLabel = params.getParameter("goodsLabel");
String goodsDesc = params.getParameter("goodsDesc");
String goodsName = params.getParameter("goodsName");
String price = params.getParameter("price");
如果报错:
org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.Mult…
就改用:
MultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());
MultipartHttpServletRequest params = resolver.resolveMultipart(request);