@RequestBody
with Multipart (file + JSON) returns 403I’m making a small Spring Boot test project where I want to update a user’s profile data (name, email, and image).
If I send the request in Postman using form-data
with only a file, everything works fine.
But as soon as I uncomment the @RequestBody
line and try to send both JSON and file in the same request, I get a 403 Forbidden error.
My controller method:
@PatchMapping("/{id}")
@Operation(summary = "Update user")
public ResponseEntity<User> updateUser(
@PathVariable Long id,
@RequestPart("file") MultipartFile file
// @RequestBody UserDtoRequest userDtoRequest
) {
System.out.println(id);
System.out.println(file);
// System.out.println(userDtoRequest);
return null;
}
My DTO:
@Data
@AllArgsConstructor
public class UserDtoRequest {
@Nullable
@Length(min = 3, max = 20)
private String username;
@Nullable
@Email(message = "Email is not valid")
private String email;
}
I can only accept data from UserDtoRequest
if I use raw JSON in Postman, but then I cannot attach the image.
Question:
How can I send both a file and JSON object in the same request without getting a 403 error?
@RequestBody
expects the entire request body to be JSON, which conflicts with multipart/form-data
used for file uploads.
The correct way is to use @RequestPart
for both the JSON object and the file.
@PatchMapping(value = "/{id}", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<User> updateUser(
@PathVariable Long id,
@RequestPart(value = "file", required = false) MultipartFile file,
@RequestPart(value = "user", required = false) UserDtoRequest userDtoRequest
) {
System.out.println("ID: " + id);
System.out.println("File: " + file);
System.out.println("User DTO: " + userDtoRequest);
// TODO: Save file, update user, etc.
return ResponseEntity.ok().build();
}
Method: PATCH
URL: http://localhost:8080/users/{id}
Go to Body → form-data and add:
Key: file
→ Type: File → choose an image from your computer.
Key: user
→ Type: Text → paste JSON string:
{"username":"John","email":"[email protected]"}
multipart/form-data
.@RequestPart
tells Spring to bind individual parts of a multipart request to method parameters.
This allows binary data (file) and structured data (JSON) in the same request.
Using @RequestBody
with multipart is not supported because it expects a single non-multipart payload.
✅ Tip: If Spring can’t parse the JSON in user
automatically, add:
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
or ensure that the user
field in Postman is exactly valid JSON.