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

时间:2020-02-07 10:00:55

标签: java reactjs rest spring-boot axios

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

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

前端(反应)代码:

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

教程参考:SO MK

更新的前端代码:

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]]

3 个答案:

答案 0 :(得分:0)

您无法JSON字符串化文件。据我所知,为了通过http上传文件,您必须将数据发布为表单数据。 This link's答案显示了如何在axios中发布formdata。您的Java端可能已经配置好用于表单数据输入。

答案 1 :(得分:0)

已编辑

首次异常解决方案

您正在服务器端使用multipart/form-data,因此必须以formData的形式发送数据。

使用使用const formData = new FormData(form);代替JSON.stringify


第二个例外解决方案

您的第二个例外是绑定错误,您正试图将String绑定到Multipart中,这是因为这一行

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

1-您可以在文件格式中设置onChange,例如onFileChangeHandler

<input type="file" className="form-control" name="file" onChange={this.onFileChangeHandler}/>

2-在formData中设置上传的文件并发送(如下面的代码所示)

onChange的正文可以如下

onFileChangeHandler = (e) => {
        e.preventDefault();
        this.setState({
            selectedFile: e.target.files[0]
        });
        const formData = new FormData();
        formData.append('file', this.state.selectedFile);
        //Append the rest data then send
        axios({
           method: 'post',
           url: 'myurl',
           data: formData,
           headers: {'Content-Type': 'multipart/form-data' }
        })
        .then(function (response) {
           //handle success
           console.log(response);
        }, 
        function(error) { 
           // handle error 
        });

以下链接可能对您的情况有用:

File Upload with React Js (Axios) and Spring REST

答案 2 :(得分:0)

如果你使用 html+js 作为前端。当不需要该文件时,以下可能有帮助:

a