Issue
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. 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.
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:
@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):
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:
-----------------------------174062142330182702901981377266
Content-Disposition: form-data; name="file"
[object Object]
-----------------------------174062142330182702901981377266--
Error message in Intellij:
Resolved [org.springframework.web.multipart.support.MissingServletRequestPartException: Required request part 'file' is not present]
Solution
Turns out this:
setFileAttachment({
fileAttachment: e.target.files[0]
})
Needed to be this:
setFileAttachment(e.target.files[0])
It's always the little things
Answered By - dlemp
Answer Checked By - Marie Seifert (JavaFixing Admin)