I'm sending an image file from frontend inside a FormData object. I set 'multipart/form-data' as the Content-Type of the request in the headers section of axios and set the controller in my backend to consume multipart/form-data.
But when I do the POST request, the backend returns this error: "org.springframework.web.multipart.support.MissingServletRequestPartException: Required part 'image' is not present" But if I do the request through Postman and not through my frontend, the backend recognises the MultiPartFile file.
This is the axios POST request in my frontend:
const image = new FormData();
image.append("image", payload)
response = await axiosClient.post(URL, image, {
headers: {
Authorization: `Bearer ${token}`,
'Content-Type': 'multipart/form-data'
},
validateStatus: function (status) {
return true;
}
})
And this is the HTML form where I'm getting the image:
<form>
<div>
<input type="file" id="image" name="image" accept="image/*"/>
</div>
</form>
This is the body of the request as seen in the Network tab of the browser: enter image description here
And the headers of the request in the Network tab: enter image description here
This is my backend controller (I'm using SpringBoot):
@PostMapping(value = "/{id}/image", consumes = "multipart/form-data")
@ResponseStatus(HttpStatus.CREATED)
public ResponseEntity<VideoGameDTO> addImage(@RequestParam("image") MultipartFile image, @PathVariable UUID id) throws IOException {
return new ResponseEntity<>(mapper
.toDto(addImageUseCase.addImage(image, id)), HttpStatus.CREATED);
}
And this is the request done in Postman that works: enter image description here
I don't know where the problem is because I know thanks to Postman that the backend is working properly and I can see with the Network tab of the browser that the file is sent as it should.