Well, this error is familiar, because it gave me sleepless nights. 415 Unsupported Media Type. I think this means that the content type of the request doesn't match what spring-boot expects. Since you've confirmed that your BE API works, I suspect tat the issue is in how React is making the request. Just making educated guesses here. Here are a few things you can try:
Check that the field names in your FormData match the param names in your controller. FormData (caption, file, and postTypeName)
Please check your axios version. I put this here because some versions of axios have known issues with FormData
Remove Content-Type header I think because axios automatically sets the Content-Type header to multipart/form-data with a boundary, which is essential for FormData to work properly. Manually setting Content-Type can interfere with this. So Try removing 'Content-Type': 'multipart/form-data' from the headers like this:
const response = await axios.post(url, formData, {
headers: {
"Authorization": `Bearer ${token}`,
},
});
postTypeName in FormData instead of RequestParam: Since you've currently added postTypeName as a RequestParam, it might not work as expected in a FormData object. Instead, please ensure that postTypeName is added as a RequestPart parameter in your controller. Do you understand?I would also improve your addPostWithImage endpoint like this.
@PostMapping(value = "/posts/add", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
@ResponseStatus(HttpStatus.CREATED)
@ApiResponse(responseCode = "400", description = "Please check the payload or token")
@ApiResponse(responseCode = "200", description = "Post added with image")
@Operation(summary = "Add a new Post with optional image")
@SecurityRequirement(name = "studyeasy-demo-api")
public ResponseEntity<?> addPostWithImage(
@Parameter(content = @Content(mediaType = MediaType.APPLICATION_JSON_VALUE)) @RequestPart("caption") PostPayloadDTO postPayloadDTO,
@RequestPart(value = "file", required = false) MultipartFile file,
@RequestPart("postTypeName") String postTypeName, // I changed this from RequestParam to RequestPart
Authentication authentication) {
...
}
These are some of the issues I could immediately spot with your code. Try and change them and please let me know.