Jill
Jill

Reputation: 333

Receive Image as multipart file to rest service

I am exposing a restful webservice, where i want to accept image as multipart file in the json body request i dont find anywhere a sample json request so as to hit my rest service from a rest client.my rest service uses this field above the class declaration @Consumes({MediaType.APPLICATION_JSON,MediaType.MULTIPART_FORM_DATA}) can anyone please get me a sample json request

Upvotes: 2

Views: 6093

Answers (1)

lefloh
lefloh

Reputation: 10961

The purpose of multipart/form-data is to send multiple parts in one request. The parts can have different media types. So you should not mix json and the image but add two parts:

POST /some-resource HTTP/1.1
Content-Type: multipart/form-data; boundary=AaB03x

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

{ "foo": "bar" }

--AaB03x--
Content-Disposition: form-data; name="image"; filename="image.jpg"
Content-Type: application/octet-stream

... content of image.jpg ...

--AaB03x--

With the RESTeasy client framework you would create this request like this:

WebTarget target = ClientBuilder.newClient().target("some/url");
MultipartFormDataOutput formData = new MultipartFormDataOutput();
Map<String, Object> json = new HashMap<>();
json.put("foo", "bar");
formData.addFormData("json", json, MediaType.APPLICATION_JSON_TYPE);
FileInputStream fis = new FileInputStream(new File("/path/to/image"));
formData.addFormData("image", fis, MediaType.APPLICATION_OCTET_STREAM_TYPE);
Entity<MultipartFormDataOutput> entity = Entity.entity(formData, MediaType.MULTIPART_FORM_DATA);
Response response = target.request().post(entity);

Which can be cosumed like this:

@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(MultipartFormDataInput input) throws Exception {
    Map<String, Object> json = input.getFormDataPart("json", new GenericType<Map<String, Object>>() {});
    InputStream image = input.getFormDataPart("image", new GenericType<InputStream>() {});
    return Response.ok().build();
}

Upvotes: 3

Related Questions