[英]React Spring Boot App Using Multipart Form Data - Required request part 'file' is not present
After days of attempting to upload a file using a React frontend and Spring Boot backend, I'm coming here to see if anyone can guide me in the right direction.经过几天尝试使用 React 前端和 Spring 引导后端上传文件后,我来这里看看是否有人可以指导我正确的方向。 Everything seems to be in place - I select my file, I see the file properties in the console, and I see form data being passed to the REST API, but I still get an error.一切似乎都已到位 - 我 select 我的文件,我在控制台中看到文件属性,并且我看到表单数据正在传递给 REST API,但我仍然得到一个错误。
Some React snippets:一些反应片段:
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}/>
Some Spring Boot snippets:一些 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 data for console.log(fileAttachment): 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: ""
Request sent to rest api:发送至 rest api 的请求:
-----------------------------174062142330182702901981377266
Content-Disposition: form-data; name="file"
[object Object]
-----------------------------174062142330182702901981377266--
Error message in Intellij: Intellij 中的错误消息:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]已解决 [org.springframework.web.multipart.support.MissingServletRequestPartException:所需的请求部分“文件”不存在]
You should enable multipart in application.properties file:您应该在 application.properties 文件中启用 multipart:
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size = -1
spring.servlet.multipart.max-request-size=-1
Also, don't forget to set the 'Content-Type':'multipart/form-data'
in request header while sending your request.另外,发送请求时不要忘记在请求 header 中设置'Content-Type':'multipart/form-data'
。
Turns out this:结果是这样的:
setFileAttachment({
fileAttachment: e.target.files[0]
})
Needed to be this:需要是这样的:
setFileAttachment(e.target.files[0])
It's always the little things总是小事
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.