File Upload with Additional Data in Jersey RESTful Web Service
To achieve file upload along with other object data in a single REST call, modify the uploadFileWithData method as follows:
@POST @Path("/upload2") @Consumes({MediaType.MULTIPART_FORM_DATA, MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response uploadFileWithData( @FormDataParam("file") InputStream fileInputStream, @FormDataParam("file") FormDataContentDisposition contentDispositionHeader, @FormDataParam("emp") String employeeJson) { // Deserialize the employee data from JSON JacksonJsonProvider provider = new JacksonJsonProvider(); Employee emp = provider.readFrom(Employee.class, employeeJson); // ...business logic... }
Key Points:
Postman Troubleshooting:
Postman may not automatically set Content-Types for individual body parts. To fix this:
Alternative Solution:
Alternatively, you can set the Content-Type explicitly in your REST method:
@POST @Path("/upload2") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFileAndJSON( @FormDataParam("emp") FormDataBodyPart jsonPart, @FormDataParam("file") FormDataBodyPart bodyPart) { jsonPart.setMediaType(MediaType.APPLICATION_JSON_TYPE); Employee emp = jsonPart.getValueAs(Employee.class); // ...business logic... }
Note:
If you are using a different Connector than HttpUrlConnection, you may encounter issues as discussed in the associated comments.
The above is the detailed content of How to Upload Files with Additional JSON Data in a Jersey RESTful Web Service?. For more information, please follow other related articles on the PHP Chinese website!