0

I have a Jersey REST API. I want to be able to send a JSON post request to the server with parameters

{ name:"abc", description:"test"} . 

ALong with these parameters, I also want to send a file through my post request. I am not sure how to achieve following:

  1. To send file and other parameters in a single JSON object on the client side.
  2. To receive them on the server side.

I have read that MULTIPART_FORM_DATA can be used for this. Need help to determine how to use it.

My server code is

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response create(JSONObject input) {
  ObjectMapper mapper = new ObjectMapper();
  Simulation config = mapper
   .readValue(input.toString(), Simulation.class);
  if (!CreateSimulation.isVaild(config))
  {
    ResponseBuilder builder = Response.status(Response.Status.BAD_REQUEST);
    builder.entity("Bad Request: Wrong Parameters");
    Response response = builder.build();
    throw new WebApplicationException(response);
  }
  int id = CreateSimulation.create(config);
  JSONObject output = new JSONObject();
  output.put("simulation-id", id + "");
  return Response.ok(output.toString(), MediaType.APPLICATION_JSON).build();
}
user2694377
  • 85
  • 1
  • 1
  • 7

2 Answers2

0

Encode file as base64 and send it as text.

Marcin Szymczak
  • 11,199
  • 5
  • 55
  • 63
0

Another way is to read file into bytes at the client. Then send the bytes to the REST service as application/octet-stream

Sample code is here from my post on another thread. The service receives bytes from a file, zips the file and returns the zipped bytes. https://stackoverflow.com/a/32253028/15789

Hope this helps you.

Community
  • 1
  • 1
RuntimeException
  • 1,593
  • 2
  • 22
  • 31