0

I'm new to Spring...I have a Spring Boot API application and all of my methods (POST, GET, etc) work great with Postman when the Content-Type is set to application/json, I can send and receive JSON.

However, I'd really like for my methods to also accept a GET or POST in the browser. When I use the browser to do a GET, the API returns an INTERNAL_SERVER_ERROR. I created a small form and try to POST to my API, but then I get the UNSUPPORTED_MEDIA_TYPE: Content type 'multipart/form-data;boundary=--------------------------802438220043016845671644;charset=UTF-8' not supported

These are 2 of the methods in my @RestController:

@RequestMapping(method = RequestMethod.POST, value = {"","/"})
public ResponseEntity<MyModel> createModel(@Valid @RequestBody MyModelDto modelDto) {
    MyModel model = modelService.createModel(modelDto);
    URI createdModelUrl = ServletUriComponentsBuilder.fromCurrentRequest().path("/{identifier}")
            .buildAndExpand(model.getIdentifier()).normalize().toUri();
    return ResponseEntity.created(createdModelUrl).build();

@RequestMapping(method = RequestMethod.GET, value = "/{identifier}")
public Resource<MyModel> getByIdentifier(@PathVariable("identifier") String identifier) {
    MyModel model = modelService.getByIdentifier(identifier);
    Resource<MyModel> resource = new Resource<>(model);
    return resource;
}

If there's any other code that would be helpful to show, let me know and I'll update the thread.

4

3 Answers 3

2

In createModel method, instead of @RequestBody, please use @ModelAttribute for MyModelDto parameter.

1
  • Just this change and it worked. Aug 8, 2022 at 8:04
0

You can use can try following ways,

Set consume block in "@RequestMapping".

like , @RequestMapping(value="/abc", consume = "multipart/form-data", method=HTTPMethod.POST")

Use @Multipart annotation and file object as @Part annotation

Instead of use @RequestBody use @RequestPart.

3
  • how can i use it in postman then?
    – Rajanboy
    Jul 9, 2022 at 17:15
  • Create one DTO which contains your part file & your current entity as a string. Replace it with your current request param and after getting this you can convert your string DTO value to your real entity. Same way in postman you can pass two variables one is a multipart file and the other is your data JSON as a string Aug 18, 2022 at 3:31
  • I'll share example once I get some free time. Aug 18, 2022 at 3:31
0
@PostMapping(value = "/upload", consumes = "multipart/form-data") 
1
  • 1
    Are you sure that the OP knows where to place this annotation in his code?
    – Abra
    Aug 26 at 5:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.