簡體   English   中英

react + spring boot 上傳文件和表單數據

[英]react + spring boot upload file and form data

我的表格中有一個案例(前端),我可以填寫個人數據(姓名、地址、出生日期),然后我可以附加多個圖像。

在我的 spring 啟動 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);
}

我的 model 包裝:

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:Stream 關閉且附件長度為零/附件大小為零(從 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]]

你不能 JSON 字符串化文件。 據我所知,為了通過 http 上傳文件,您必須將數據作為表單數據發布。 此鏈接的答案顯示了如何在 axios 中發布表單數據。 您的 java 端可能已經配置為表單數據輸入。

已編輯

第一個異常解決方案

您正在服務器端使用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 
        });

以下鏈接可能對您的情況有用:

使用 React Js (Axios) 和 Spring REST 上傳文件

如果您使用 html+js 作為前端。 當不需要文件時,以下可能有幫助:

var formData = new FormData(document.getElementById("yourFormId"));

我遇到這個問題是因為 react 中的表單實現錯誤。

我試圖一次附加所有圖像。

formData.append("images", images)

循環圖像后,它解決了我的問題

for (let i = 0 ; i < images.length ; i++) {
    formData.append("images", images[i]);
}

哦,好吧。。我明白了

在此處輸入圖像描述

在每個數組中,存在 Multipart 中 spring 引導轉換器的 File 屬性

我的js中的代碼:

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM