92
votes

I need to receive an HTTP Post Multipart which contains only 2 parameters:

  • A JSON string
  • A binary file

Which is the correct way to set the body? I'm going to test the HTTP call using Chrome REST console, so I'm wondering if the correct solution is to set a "label" key for the JSON parameter and the binary file.

On the server side I'm using Resteasy 2.x, and I'm going to read the Multipart body like this:

@POST
@Consumes("multipart/form-data")
public String postWithPhoto(MultipartFormDataInput  multiPart) {
  Map <String, List<InputPart>> params = multiPart.getFormDataMap();
  String myJson = params.get("myJsonName").get(0).getBodyAsString();
  InputPart imagePart = params.get("photo").get(0);
  //do whatever I need to do with my json and my photo
}

Is this the way to go? Is it correct to retrieve my JSON string using the key "myJsonName" that identify that particular content-disposition? Are there any other way to receive these 2 content in one HTTP multipart request?

Thanks in advance

1
What kind of REST resource is this? How do two parts relate on the resource level?user647772
Actually the way we handled this resource is not totally RESTful because the image is a "component" of the resource instead of another resource.thermz

1 Answers

152
votes

If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes. You set request header Content-Type: multipart/form-data; boundary=HereGoes. Then this should be a valid request body:

--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json

{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64

<...JPEG content in base64...>
--HereGoes--