[英]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 列表切換)。 請對此案例有所了解,因為很多教程僅用於上傳附件部分,不包括用戶填寫的表單數據。 之前謝謝。
更新的前端代碼:
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
});
以下鏈接可能對您的情況有用:
如果您使用 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]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.