Multipart content handling

RESTEasy provides abstraction of multipart content handling with the multipart data provider plugin. This plugin enables you to easily parse the uploaded content submitted via HTML forms. To use the plugin, include the following Maven dependencies in the POM file:

 <dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
<version>RELEASE</version>
</dependency>

Let's try with the simple use case of an employee uploading/downloading his/her profile picture. For this use case, we will create a simple HTML form for the employee to upload his/her profile picture, as shown ahead:

<html>
<body>
<h1>Upload Employee Profile Picture</h1>

<form action="webresources/employee/addimage" method="post" enctype="multipart/form-data">
<p>
Employee Id : <input type="text" name="employeeId" size="50" />
</p>
<p>
Select Profile Image : <input type="file" name="profilePicture" size="50" />
</p>
<p>
Description : <input type="text" name="imageDesc" size="50" />
</p>
<input type="submit" value="Upload Image" />
</form>

</body>
</html>

Please make sure that the form attribute, enctype, is specified as multipart/form-data. Once the user submits the form, the request is submitted to the EmployeeImageResoure class's addImage operation. The org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput argument of the addImage operation will be used to read the submitted form contents. Similarly, to download the image, the user can use the getProfilePicture operation, which wraps the image file in the response using the javax.ws.rs.core.Response.ResponseBuilder class, as shown ahead:

/**
* This class used to upload or download an employee profile picture
*
*/
@Path("employee")
@Stateless
public class EmployeeImageResource {

@PersistenceContext(unitName = "com.packtpub_rest-chapter5-resteasy-service_war_1.0-SNAPSHOTPU")
private EntityManager entityManager;
private static final Logger logger = Logger.getLogger(EmployeeImageResource.class.getName());

@GET
@Path("/image/{id}")
@Produces("image/png")
/*
* Download the employee profile picture for the given employee id
*/
public Response getProfilePicture(@PathParam("id") Short empId) {

try {

//Step-1: Fetch the employee profile picture from datastore
EmployeeImage profile = entityManager.find(EmployeeImage.class, empId);

//Ste-2:
String fileName = empId + "-image.png";
File imageFile = new File(fileName);
try (FileOutputStream imageFOS = new FileOutputStream(imageFile)) {
imageFOS.write(profile.getEmployeePic());
imageFOS.flush();
}

ResponseBuilder responseBuilder = Response.ok((Object) imageFile);
responseBuilder.header("Content-Disposition", "attachment; filename="" + fileName + """);
return responseBuilder.build();
} catch (IOException e) {
logger.log(Level.SEVERE, "Error Fetching Employee Profile Picture", e);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error Fetching Employee Profile Picture").build();
}

}


@POST
@Consumes("multipart/form-data")
@Path("/addimage")
/*
* Upload the employee profile picture for the given employee id
*/
public Response addImage(MultipartFormDataInput form) {

try {
//Step-1: Read the Form Contents
Map<String, List<InputPart>> formContents = form.getFormDataMap();
List<InputPart> imagePart = formContents.get("profilePicture");

if (imagePart == null) {
return Response.status(400).entity("Invalid Content Uploaded").build();
}
byte[] profilePic = null;

for (InputPart inputPart : imagePart) {

profilePic = IOUtils.toByteArray(inputPart.getBody(InputStream.class, null));
}

//Step-2: Validate the presence of mandatory content and
//if invalid content reply as Bad Data Request
if (profilePic == null || profilePic.length<1 || formContents.get("employeeId") == null) {
return Response.status(Status.BAD_REQUEST).entity("Invalid Content Uploaded").build();
}

String empId = formContents.get("employeeId").get(0).getBodyAsString();
String desc = "";
if (formContents.get("imageDesc") != null
&& formContents.get("imageDesc").get(0) != null) {
desc = formContents.get("imageDesc").get(0).getBodyAsString();
}

//Step-3:Persist the uploaded image to datastore
EmployeeImage empImgEntity = new EmployeeImage(
Short.parseShort(empId),
profilePic, desc);
entityManager.persist(empImgEntity);

return Response.status(Status.CREATED).entity("Saved Employee Profile Picture").build();

} catch (IOException | NumberFormatException e) {
logger.log(Level.SEVERE, "Error Saving Employee Profile Picture", e);
return Response.status(Status.INTERNAL_SERVER_ERROR).entity("Error Saving Employee Profile Picture").build();

}

}

}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.157.197