![](/img/trans.png)
[英]How to fix "Required request part is not present" in a Spring Boot multipart upload
[英]React Spring Boot App Using Multipart Form Data - Required request part 'file' is not present
經過幾天嘗試使用 React 前端和 Spring 引導后端上傳文件后,我來這里看看是否有人可以指導我正確的方向。 一切似乎都已到位 - 我 select 我的文件,我在控制台中看到文件屬性,並且我看到表單數據正在傳遞給 REST API,但我仍然得到一個錯誤。
一些反應片段:
const onFileChangeHandler = (e) => {
e.preventDefault();
setFileAttachment({
fileAttachment: e.target.files[0]
})};
const formData = new FormData();
formData.append('file',fileAttachment)
const requestOptionsInsertNote = {
method: "POST",
body: formData
};
<input type="file" name="file" onChange={onFileChangeHandler}/>
一些 Spring 引導片段:
@PostMapping( "/api/notes/insertNote")
public void insertJournalNote(@RequestPart(value="file") MultipartFile file{
UploadedFileInfo uploadedFileInfo = new UploadedFileInfo();
try{
uploadedFileInfo.setFileData(file.getBytes());
uploadedFileInfo.setFileType(file.getContentType());
uploadedFileInfo.setFileName(file.getOriginalFilename());
}catch (IOException e){
e.printStackTrace();
}}
console.log(fileAttachment) 的控制台日志數據:
Object { fileAttachment: File }
fileAttachment: File { name: "file.jpg", lastModified: 1650655091391, size: 148823, … }
lastModified: 1650655091391
name: "file.jpg"
size: 148823
type: "image/jpeg"
webkitRelativePath: ""
發送至 rest api 的請求:
-----------------------------174062142330182702901981377266
Content-Disposition: form-data; name="file"
[object Object]
-----------------------------174062142330182702901981377266--
Intellij 中的錯誤消息:
已解決 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的請求部分“文件”不存在]
您應該在 application.properties 文件中啟用 multipart:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size = -1
spring.servlet.multipart.max-request-size=-1
另外,發送請求時不要忘記在請求 header 中設置'Content-Type':'multipart/form-data'
。
結果是這樣的:
setFileAttachment({
fileAttachment: e.target.files[0]
})
需要是這樣的:
setFileAttachment(e.target.files[0])
總是小事
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.