I'm using Postman to send the following request:
My controller looks like this:
@RestController
@RequestMapping(path = RestPath.CHALLENGE)
public class ChallengeController {
private final ChallengeService<Challenge> service;
@Autowired
public ChallengeController(ChallengeService service) {
this.service = service;
}
@ApiOperation(value = "Creates a new challenge in the system")
@RequestMapping(method = RequestMethod.POST, consumes = {MediaType.MULTIPART_FORM_DATA_VALUE, MediaType.APPLICATION_OCTET_STREAM_VALUE},
produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.CREATED)
public ChallengeDto create(@ApiParam(value = "The details of the challenge to create") @RequestPart("challengeCreate") @Valid @NotNull @NotBlank ChallengeCreateDto challengeCreate,
@ApiParam(value = "The challenge file") @RequestPart("file") @Valid @NotNull @NotBlank MultipartFile file) {
return service.create(challengeCreate, file);
}
}
I already tried to change the "consumes" to delete the APPLICATION_OCTET_STREAM_VALUE to MULTIPART_FORM_DATA_VALUE and also tried to delete it, but none of these helped.
Please tell me if you need more information. Thanks.
@Rokin Answer is good but dont need to place json in file and upload. You can achieve by passing content type to json object as well. Postman support content type options while sending form-data. for further see the below image which is self descriptive.
For Spring's @RequestPart to work with json objects, in Postman - you need to send the json object as a File instead of Text.
Put the contents of ChallengeCreateDto in a json file and save it as challenge.json. Then upload this file in Postman with the type as File. I've attached a screenshot of how the request in Postman should be just to make it more clearer.
You can also use @PostMapping instead of @RequestMapping in the newer versions of Spring as shown here
@ResponseStatus(HttpStatus.CREATED)
@PostMapping()
public ChallengeDto create(@RequestPart("challengeCreate") ChallengeCreateDto challengeCreate,
@RequestPart("file") MultipartFile file) {
return service.create(challengeCreate, file);
}
Using @RequestParam to get string and file will solve this issue. In Postman use Content-Type as "multipart/form-data" and in Body define your input as form-data.
Refer https://stackoverflow.com/a/38336206/1606838
Example:
@PostMapping(consumes = {"multipart/form-data"})
public Output send(@RequestParam String input, @RequestParam MultipartFile file) {
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With