![](/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.