Home >Java >javaTutorial >How to Upload a File and JSON Data Simultaneously in a Jersey RESTful Web Service?

How to Upload a File and JSON Data Simultaneously in a Jersey RESTful Web Service?

Susan Sarandon
Susan SarandonOriginal
2024-12-06 14:44:11734browse

How to Upload a File and JSON Data Simultaneously in a Jersey RESTful Web Service?

File Upload Along with Other Object in Jersey RESTful Web Service

Problem:

You want to create an employee record with image and employee data in a single REST API call using Jersey, but the current implementation raises an error in Chrome Postman.

Answer:

To enable simultaneous file upload and JSON data transmission, the JSON data must be included in the multipart request. Here's a modified version of your code snippet:

@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

}

The key change is the addition of @FormDataParam("emp") to include the employee data in the multipart request.

Additional Notes:

  • If you encounter the error "No injection source found for a parameter of type public javax.ws.rs.core.Response" while using the new code, ensure that the proper Jersey configurations for handling multipart requests are in place in your server code.
  • Some REST clients, like the browser's default FormData capabilities, may not support setting Content-Types for individual multipart parts. To address this, you can explicitly set the Content-Type for the JSON part before deserializing the data on the server side:
@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);
}

The above is the detailed content of How to Upload a File and JSON Data Simultaneously in a Jersey RESTful Web Service?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn