Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST Service that can consume both JSON and Multipart Form

I need to create a method in Spring MVC that can handle both JSON and Multipart Form requests.

This is my method's signature:

@RequestMapping(value = { "/upload_image" }, method = RequestMethod.POST)
public @ResponseBody void uploadImage(final ImageDTO image) 

ImageDTO class looks as following:

public class ImageDTO {
  private String imageUrl;
  private Long imageId;
  private MultipartFile image;

  public String getImageUrl() {
    return imageUrl;
  }

  public void setImageUrl(final String url) {
    this.imageUrl = url;
  }

  public Long getImageId() {
    return imageId;
  }

  public void setImageId(final Long imageId) {
    this.imageId = imageId;
  }

  public MultipartFile getImage() {
    return image;
  }

  public void setImage(MultipartFile image) {
    this.image = image;
  }
}

So the scenario is that I need to support two scenarios: 1. Image up load from form, where the Content-Type is multipart-form (all DTO members are not null) 2. Image upload using JSON, using ONLY the imageUrl. In this case, the request body looks like this:

{
    "imageId":"1236",
    "imageUrl":"http://some.image.url",
    "image":null
}

The current implementation handles the multipart request well, but when sending the JSON, the ImageDTO object contains NULLs in all its members.

Is is it possible to make the same method handle both content types?

Thank you.

like image 935
Irit Rolnik Avatar asked Jan 21 '15 08:01

Irit Rolnik


People also ask

How do you send the multipart file and JSON data to spring boot?

To pass the Json and Multipart in the POST method we need to mention our content type in the consume part. And we need to pass the given parameter as User and Multipart file. Here, make sure we can pass only String + file not POJO + file. Then convert the String to Json using ObjectMapper in Service layer.

Is multipart form data restful?

Multipart/Form-Data is a popular format for REST APIs, since it can represent each key-value pair as a “part” with its own content type and disposition. Each part is separated by a specific boundary string, and we don't explicitly need Percent Encoding for their values.


1 Answers

To receive JSON you need to mark ImageDTO argument with @RequestBody

@RequestMapping(value = { "/upload_image" }, method = RequestMethod.POST)
public @ResponseBody void uploadImage(final @RequestBody ImageDTO image) 
like image 200
shazin Avatar answered Oct 25 '22 18:10

shazin