79729809

Date: 2025-08-08 13:26:59
Score: 2
Natty:
Report link

Spring Boot @RequestBody with Multipart (file + JSON) returns 403

I’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?


Solution

@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.

Updated Controller:

@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();
}

How to send the request in Postman:

  1. Method: PATCH

  2. URL: http://localhost:8080/users/{id}

  3. 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]"}

  1. Postman will automatically set the Content-Type to multipart/form-data.

Why this works:


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.

Reasons:
  • Blacklisted phrase (0.5): How can I
  • Blacklisted phrase (0.5): I cannot
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • Has code block (-0.5):
  • Contains question mark (0.5):
  • Low reputation (1):
Posted by: WordPressNaimur