react上传java_Java - react+springboot上传文件和表单数据_java_酷徒编程知识库

本文介绍了如何在Spring Boot后端处理来自React前端的文件和表单数据上传。通过示例代码展示了在控制器中接收`multipart/form-data`请求,以及前端如何使用`FormData`正确构造请求。同时,文中提到了一个常见的错误,即前端将`FileList`对象转换为字符串导致的类型匹配失败,并给出了相应的解决方法。
摘要由CSDN通过智能技术生成

在Spring Boot控制器中:@RequestMapping(value ="/addCustOrder", method = RequestMethod.POST, consumes = {"multipart/form-data"})

public String CustomerOrder(@ModelAttribute CustOrderRequest coReq, HttpServletRequest request) {

System.out.println("debug **************");

System.out.println("ReceiverName ::" + coReq.getReceiverName());

System.out.println("attachmentFile ::" + coReq.getFileAttachment().length);

}

模型包装器:public class CustOrderRequest {

private String receiverName;

private String receiverPhone;

private String itemDescription;

private MultipartFile[] fileAttachment;

}

//setter & getter

前端(React )代码:const payload = JSON.stringify({

id: values.id,

receiverName: values.receiverName,

receiverPhone: values.receiverPhone,

itemDescription: values.itemDescription,

fileAttachment: values.fileAttachment

});

axios.post(urlApi, payload)

.then(r => {

// success request

});

在上面的示例中,我总是遇到错误,

教程参考:SOMK

前端代码:let fd = new FormData();

fd.append("fileAttachment", values.fileAttachment);

fd.append("receiverName", values.receiverName);

axios.post(urlApi, fd)

.then(r => {

// success request

});

使用formdata更改了前端代码,然后在后端得到错误:2020-02-07T17:36:10.231+0700 WARN Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors

Field error in object 'custOrderRequest' on field 'fileAttachment': rejected value [[object FileList]]; codes [typeMismatch.custOrderRequest.fileAttachment,typeMismatch.fileAttachment,typeMismatch.[Lorg.springframework.web.multipart.MultipartFile;,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [custOrderRequest.fileAttachment,fileAttachment]; arguments []; default message [fileAttachment]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile[]' for property 'fileAttachment'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'org.springframework.web.multipart.MultipartFile' for property 'fileAttachment[0]': no matching editors or conversion strategy found]]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值