File upload example in Jersey
In this tutorial, we show you how do to file upload with Jersey, JAX-RS implementation.
1. Jersey Multipart Dependency
To support multipart (file upload) in Jersey, you just need to include “jersey-multipart.jar” in Maven pom.xml file.
<project ...> <repositories> <repository> <id>maven2-repository.java.net</id> <name>Java.net Repository for Maven</name> <url>http://download.java.net/maven/2/</url> <layout>default</layout> </repository> </repositories> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-server</artifactId> <version>1.8</version> </dependency> <dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>1.8</version> </dependency> </dependencies> </project>
2. File Upload HTML Form
Simple HTML form to select and upload a file.
<html> <body> <h1>File Upload with Jersey</h1> <form action="rest/file/upload" method="post" enctype="multipart/form-data"> <p> Select a file : <input type="file" name="file" size="45" /> </p> <input type="submit" value="Upload It" /> </form> </body> </html>
3. Upload Service with Jersey
In Jersey, use @FormDataParam to receive the uploaded file. To get the uploaded file name or header detail, match it to “FormDataContentDisposition“.
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import javax.ws.rs.Consumes; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import com.sun.jersey.core.header.FormDataContentDisposition; import com.sun.jersey.multipart.FormDataParam; @Path("/file") public class UploadFileService { @POST @Path("/upload") @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "d://uploaded/" + fileDetail.getFileName(); // save it writeToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded to : " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = new FileOutputStream(new File( uploadedFileLocation)); int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) { out.write(bytes, 0, read); } out.flush(); out.close(); } catch (IOException e) { e.printStackTrace(); } } }
4. Demo
Select a file and click on the upload button, the selected file is uploaded to a pre-defined location.
URL : http://localhost:8080/RESTfulExample/FileUpload.html

URL : http://localhost:8080/RESTfulExample/rest/file/upload








getting HTTP Status 415 – Unsupported Media Type error , anyone know how to fix this ?
How can I upload the file using CURL instead of the HTML webpage ?
It’s possible to perform a file upload and receive a JSON object?
suppose:
@POST
@Path(“/sendCollect”)
@Consumes({MediaType.MULTIPART_FORM_DATA,MediaType.APPLICATION_JSON})
public Response sendCollect( @FormDataParam(“img”) InputStream uploadedInputStream,@FormDataParam(“img”) FormDataContentDisposition fileDetail,CollectBean desc) {
return Response.status(200).entity(“1″).build();
}
For those of you trying the code above and are getting exceptions when you deploy to Tomcat, change the @Path element on the method from
to
. That fixed it for me and it works like a charm.
Thanks,
I spend some time and did not understand what i’m getting the following exception:
SEVERE: A message body reader for Java class com.sun.jersey.multipart.FormDataMultiPart.
This post was very helpful.
I added the following dependency and that solve the problem:
org.jvnet
mimepull
1.3
When i try the above examples i got the below error message, could you please kindly help to resolve this issue….
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.mkyong.rest.UploadFileService.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 0
SEVERE: Missing dependency for method public javax.ws.rs.core.Response com.mkyong.rest.UploadFileService.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 1
SEVERE: Method, public javax.ws.rs.core.Response com.mkyong.rest.UploadFileService.uploadFile(java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), annotated with POST of resource, class com.mkyong.rest.UploadFileService, is not recognized as valid resource method.
Mar 1, 2012 12:54:26 PM org.apache.catalina.core.ApplicationContext log
SEVERE: StandardWrapper.Throwable
com.sun.jersey.spi.inject.Errors$ErrorMessagesException
at com.sun.jersey.spi.inject.Errors.processErrorMessages(Errors.java:170)
at com.sun.jersey.spi.inject.Errors.postProcess(Errors.java:136)
Hi,
I was trying to use your example using tomcat server, but it looks some weired error is thrown –>
This is your uploader service class – exact same as yours –>
Also, in web.xml, it shows some error notification
@ tag, which says com.sun.jersey.spi.container.servlet.ServletContainer is not assignable to javax.servlet.Servlet..
Can you please guide, what the error is????
My requirement is to upload a file to a ftp server using a web service and that too without using a http request. because i want my SOA customers to just call the webservice and upload the file.
I am running the sample code only slightly modified. I get the following error when Jetty starts up. I have been unable to determine what is wrong by searching. Anyhelp is appreciated. The source code compiles fine. i am using all jars from version 1.11 of jersey.
SEVERE: The following errors and warnings have been detected with resource and/or provider classes:
SEVERE: Missing dependency for method public java.lang.String com.quantum.dxi.rest.FileUpload.uploadFile(javax.servlet.http.HttpServletRequest,java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 1
SEVERE: Missing dependency for method public java.lang.String com.quantum.dxi.rest.FileUpload.uploadFile(javax.servlet.http.HttpServletRequest,java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition) at parameter at index 2
SEVERE: Method, public java.lang.String com.quantum.dxi.rest.FileUpload.uploadFile(javax.servlet.http.HttpServletRequest,java.io.InputStream,com.sun.jersey.core.header.FormDataContentDisposition), annotated with POST of resource, class com.quantum.dxi.rest.FileUpload, is not recognized as valid resource method.
This was extremely helpful.
Couple of stupid issues I ran into –
1. I wasn’t using the same version of Jersey-server.jar & jersey-multipart.jar – that was stupid but in case someone else has a problem, i’d like to share that as a comment.
2. you need to include mimepull.jar in your classpath. else you get this error:
————-
SEVERE: A message body reader for Java class com.sun.jersey.multipart.FormDataMultiPart, and Java type class com.sun.jersey.multipart.FormDataMultiPart, and MIME media type multipart/form-data; ….
————
Download mimepull.jar from: http://www.java2s.com/Code/Jar/STUVWXYZ/Downloadmimepulljar.htm
Thanks for this post! this helped me lots!
Regards,
Savio
nice. but
what to do with filenames containing umlauts ISO-8859-1 encoded?
all i get are those diamond shaped thinmgumabobs with an question mark inside odr simply questionmarks.
for normal text fields i could solve that with
byte[] fieldValue = getValueAs(byte[].class);
String field = new String(new String(fieldValue, “ISO-88591-1″).getBytes(), “UTF-8″);
but that does not work with the filename (not even filename.getBytes() or filename.getBytes(“ISO-8859-1″)).
it would be nice if you could ping me per mail when you got an answer ;-)
[...] output excel file for user to download.File Upload ExamplesHow to handle multipart data in JAX-RS.File upload example in Jersey File upload is easy in Jersey.File upload example in RESTEasy Two ways to handle file upload in [...]