File Upload with Accompanying Data in Jersey RESTful Web Service
When creating employees in a system, you may wish to include an image along with their personal information. While it is possible to accomplish this with separate REST calls, it is more efficient to do so with a single call. This article provides a solution to this problem, allowing you to receive both the file and employee data simultaneously.
To achieve this, modify the Java method as follows:
@POST @Path("/upload2") @Consumes({MediaType.MULTIPART_FORM_DATA}) public Response uploadFileWithData( @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("emp") Employee emp) { // ..... business login }
In the JSON structure, the employee data is now a part of the multipart request:
{ "emp": { "Name": "John", "Age": 23, "Email": "[email protected]", "Adrs": { "DoorNo": "12-A", "Street": "Street-11", "City": "Bangalore", "Country": "Karnataka" } } }
Additional Considerations
jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE); Employee emp = jsonPart.getValueAs(Employee.class);
By following these steps, you can successfully upload a file and the accompanying employee data in a single REST call using Jersey.
The above is the detailed content of How to Upload Files and Accompanying Data Simultaneously in a Jersey RESTful Web Service?. For more information, please follow other related articles on the PHP Chinese website!