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:
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();
}
将文件编码为base64并以文本形式发送。
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.