【发布时间】:2020-05-23 10:51:45
【问题描述】:
我的表格中有一个案例(前端),我可以填写个人数据(姓名、地址、出生日期),然后我可以附加多个图像。
在我的 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
});
在上面的例子中,我总是遇到错误。像:java.io.IOException:流已关闭且附件长度为零/附件大小为零(已从 MultipartFile 数组或 MultipartFile 列表切换)。 请对此案例有所了解,因为很多教程仅用于上传附件部分,不包括用户填写的表单数据。之前谢谢。
更新前端代码:
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]]
【问题讨论】:
-
文件很大吗?文件以什么格式发送?您能否在 .then() 之后添加 .catch((err) => { console.log(err.message) }) 并告诉它何时显示或显示该帖子的浏览器调试器网络结果?您是否尝试过将文件作为二进制(字符串)发送,然后在后端编译? JSON.stringify 文件看起来很奇怪。
-
对不起,是的,它不适合 JSON.stringify 附件。我已更改代码以使用 formdata。它抛出另一个错误。
标签: java reactjs rest spring-boot axios