react + spring boot上传文件和表单数据


在我的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);


public class CustOrderRequest {
    private String receiverName;
    private String receiverPhone;
    private String itemDescription;
    private MultipartFile[] fileAttachment;
//setter & getter 


const payload = JSON.stringify({
    receiverName: values.receiverName,
    receiverPhone: values.receiverPhone,
    itemDescription: values.itemDescription,
    fileAttachment: values.fileAttachment
});, payload)
    .then(r => {
    // success request 

在上面的示例中,我总是遇到错误。像流关闭且附件长度为零/附件大小为零(已从MultipartFile数组或MultipartFile列表切换)。 请针对这种情况进行说明,因为那里有很多教程仅用于上传附件部分,不包括用户填写的表单数据。之前谢谢。

tutorial reference : SO MK

  • nrerum
    nrerum 回复

    You cant JSON stringify files. As far as I know in order to upload files through http you must post the data as form data. This link's answer shows how to post formdata in axios. Your java end is probably already configured for form data input.