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

我有一个类似我的表格(前端)的案例,我可以填写个人数据(姓名,地址,DOB),然后可以附加多个图像。

在我的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({
    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列表切换)。 请针对这种情况进行说明,因为那里有很多教程仅用于上传附件部分,不包括用户填写的表单数据。之前谢谢。

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.