Jersey File Upload

Jersey maven multipart dependency


Add Jersey MultiPartFeature in web.xml

Further, you are required to add MultiPartFeature in Jersey configuration to let it know that you will use multipart requests.


Write Jersey File Upload REST API

public class UploadService {
	@Consumes({ MediaType.MULTIPART_FORM_DATA })
	public Response uploadJpgFile(
			@FormDataParam("file") InputStream fileInputStream,
			@FormDataParam("file") FormDataContentDisposition fileMetaData)
			throws Exception {
		try {
			int read = 0;
			byte[] bytes = new byte[1024];
			OutputStream out = new FileOutputStream(
					new File(Globals.UPLOAD_PATH + fileMetaData.getFileName()));
			while ((read = != -1) {
				out.write(bytes, 0, read);
		} catch (IOException e) {
			throw new WebApplicationException(
					"Error while uploading file. Please try again !!");
		return Response
				.ok(fileMetaData.getFileName() + " uploaded successfully !!")

Test file upload using HTML Form

<form action="rest/upload/jpg" method="post" enctype="multipart/form-data">
	<p>Select a file : <input type="file" name="file" size="45" accept=".jpg"/></p>
	<input type="submit" value="Upload JPG" />

Test file upload using jersey client

public class JerseyFileUploadTest {
	public void uploadFile() throws IOException {
		final Client client = ClientBuilder.newBuilder()
		final FileDataBodyPart filePart = new FileDataBodyPart("file",
				new File("C:/avatar.jpg"));
		FormDataMultiPart formDataMultiPart = new FormDataMultiPart();
		final FormDataMultiPart multipart = (FormDataMultiPart) formDataMultiPart
				.field("foo", "bar").bodyPart(filePart);
		final WebTarget target = client
				.target(JerseyUtil.REST_URL + "/upload/jpg");
		final Response response = target.request()
				.post(Entity.entity(multipart, multipart.getMediaType()));
		// Use response object to verify upload success