Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

REST - HTTP Post Multipart with JSON

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

like image 520
thermz Avatar asked Jan 31 '12 14:01

thermz


1 Answers

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-- 
like image 182
Vasiliy Faronov Avatar answered Sep 20 '22 17:09

Vasiliy Faronov