I am studying Spring Boot and making a small test project. I want to make a method that will change the user profile data (name, email and image). Here is an approximate draft of the method. I send the request via postman and form-data and in this form everything works fine. But as soon as I uncomment the line @RequestBody UserDtoRequest userDtoRequest
and pass other data there with a name or email, I get a 403 error.
I can only accept data from DTO if I use the raw data transfer format in Postman to JSON, but then I won't be able to attach an image
@PatchMapping("/{id}")
@Operation(summary = "Изменение пользователя")
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;
}
According to the Spring Framework @RequestBody documentation:
Form data should be read using
@RequestParam
, not with@RequestBody
which can’t always be used reliably since in the Servlet API, request parameter access causes the request body to be parsed, and it can’t be read again.
So if you wanna keep it to a single request, just send your data as form data along with the file. But if you really need JSON, you’ll have to split it into two separate calls—one for the file (form-data) and another for the JSON payload.