i have a case like in my form (front end), i can fill personal data (name, address, DOB) and then i can attach multiple image.
In my spring boot controller :
@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);
}
My model wrapper :
public class CustOrderRequest {
private String receiverName;
private String receiverPhone;
private String itemDescription;
private MultipartFile[] fileAttachment;
}
//setter & getter
Front end (React) Code :
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
});
With above example, i always encounter errors. like : java.io.IOException: Stream closed and zero attachment length / zero attachment size (have switch from array of MultipartFile or List of MultipartFile). please throw some light for this case, as a lot of tutorial out there only for upload the attachment part, not including the form data that user has filled. Thanks before.
Updated front end code :
let fd = new FormData();
fd.append("fileAttachment", values.fileAttachment);
fd.append("receiverName", values.receiverName);
axios.post(urlApi, fd)
.then(r => {
// success request
});
changed the front end code using formdata then got error in backend :
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]]