You are on page 1of 8

RESTFul Webservice: File Upload with Jersey | How To & Tutorials

Page 1 of 8

RESTFul Webservice: File Upload with Jersey


23 Thursday AUG 2012

POSTED BY PUSPENDU BANERJEE IN JAVA 22 COMMENTS Tags Java EE 6 Tutorial, jax-rs, RESTful Webservice

i 5 Votes In this tutorial, we will learn how do to file upload with Jersey, A RESTFul Webservice(JAX-RS) implementation. File upload feature of html form works by wrapping the file content inside a multipart envelope as the content type application/x-www-form-urlencoded is inefficient for sending large quantities of binary data or text containing non-ASCII characters. The content type multipart/form-data should be used for submitting forms that contain files, non-ASCII data, and binary data.

1.

Resolve Dependency
For the multipart/form-data support we need to include jersey-multipart.jar and dependencies from here [for glassfish v3.1 & upward you will find it in glassfish\modules].

2.

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials


1 2 3 4 5 6 7 8 9 10 11

Page 2 of 8

<html> <body> <h1>Upload File with RESTFul WebService</h1> <form action="rest/fileupload" method="post" enctype="multipart/form-data"> <p> Choose a file : <input type="file" name="file" /> </p> <input type="submit" value="Upload" /> </form> </body> </html>

3.

Java File Upload Client


We will use Apache HTTPClient library to resolve dependency.
1 2 3 4 5 6 7 8 9 HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost(url); FileBody fileContent= new FileBody(new File(fileName)); StringBody comment = new StringBody("Filename: " + fileName); MultipartEntity reqEntity = new MultipartEntity(); reqEntity.addPart("file", fileContent); httppost.setEntity(reqEntity); HttpResponse response = httpclient.execute(httppost); HttpEntity resEntity = response.getEntity();

4.

Create JAX-RS File Upload Service with Jersey


Jersey uses @FormDataParam to receive the uploaded file. To get the uploaded file name or header detail, compare with FormDataContentDisposition which represents a Content-Disposition header whose value is form-data.

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 import import import import import import import import import import import java.io.File; java.io.FileOutputStream; java.io.IOException; java.io.InputStream; java.io.OutputStream; javax.ws.rs.Consumes; javax.ws.rs.POST; javax.ws.rs.Path; javax.ws.rs.core.MediaType; javax.ws.rs.core.Response; com.sun.jersey.core.header.FormDataContentDisposition;

Page 3 of 8

import com.sun.jersey.multipart.FormDataParam; @Path("/fileupload") public class UploadFileService { @POST @Consumes(MediaType.MULTIPART_FORM_DATA) public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail) { String uploadedFileLocation = "c://uploadedFiles/" + fileDetail.getFileName(); // save it saveToFile(uploadedInputStream, uploadedFileLocation); String output = "File uploaded via Jersey based RESTFul Webservice to: " + uploadedFileLocation; return Response.status(200).entity(output).build(); } // save uploaded file to new location private void saveToFile(InputStream uploadedInputStream, String uploadedFileLocation) { try { OutputStream out = null; int read = 0; byte[] bytes = new byte[1024]; out = new FileOutputStream(new File(uploadedFileLocation)); while ((read = uploadedInputStream.read(bytes)) != -1) {

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials

Page 4 of 8

5.

Test Your Service


1. Deploy & Browse to {App_URL}/{File_Upload_html} 2. Upload A file and check.

6.

Source Code
You can download source-code here.

About these ads

thoughts on RESTFul Webservice: File Upload with Jersey


1. Tim said: August 30, 2012 at 2:25 pm Hi! Thanks for your post. Thats exactly what I was looking for. Tim REPLY Puspendu Banerjee said: August 30, 2012 at 4:08 pm Glad to know that! Thanks REPLY 2. latrse said: November 11, 2012 at 11:11 pm good job man REPLY 3. irajghasemi said: November 23, 2012 at 6:39 pm Hi Where can I download you source-code? REPLY Puspendu Banerjee said: http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/ 23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials

Page 5 of 8

22

November 25, 2012 at 7:08 pm Thanks for pointing out the missing download link. Copy it and paste for the time being. I shall upload source at earliest. REPLY 4. esthrim said: November 28, 2012 at 7:04 am Thanks, great sample, How about if upload/download using base64 string please give another sample i very appreciate it. REPLY Puspendu Banerjee said: November 28, 2012 at 1:22 pm Thanks! Glad to hear that. Not pretty sure, what do you mean by upload/download using base64 string. Did you mean base64 encode/decode a file pre-upload/post-download? REPLY esthrim said: November 29, 2012 at 6:52 pm yes, that is what i meant, Puspendu Banerjee said: November 29, 2012 at 9:14 pm Till date, Cross browser compatibility for accessing Dom Element File from JavaScript is quite messy. I shall try to post something on base64 encoding / decoding of file element which will be Firefox compatible, but no guarantee for IE. 5. sabarish1274 said: January 18, 2013 at 6:43 pm Am not understanding Step 3: Java File Upload Client what exactly that code does. In what name i have to add code to the class. Can you explain it a brief. REPLY 6. avitra said:

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials January 22, 2013 at 9:17 pm Hi Banerjee,

Page 6 of 8

I used the html file and file upload service, when I click the upload button from the html file I am getting following message. com.sun.jersey.spi.container.ContainerRequest getEntity 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/formdata; boundary=7ddb43920504 was not found. The registered message body readers compatible with the MIME media type are: */* -> com.sun.jersey.core.impl.provider.entity.FormProvider com.sun.jersey.core.impl.provider.entity.MimeMultipartProvider . . . com.sun.jersey.json.impl.provider.entity.JSONListElementProvider$General REPLY Puspendu Banerjee said: January 29, 2013 at 8:04 pm Looks like a serialization issue. Check the serialization library you are using. Additionally let me know the App Server/Web Container you are using. REPLY hoshangvarshney said: February 1, 2013 at 2:10 pm I am also getting the same error. Which library am I missing? 7. Sekhar said: January 25, 2013 at 2:42 pm Hi Puspendu, Thanks for the post, do you know to get Request headers in post Rest service where you will receive a file content. if so please post the piece of code. REPLY Puspendu Banerjee said: January 29, 2013 at 8:07 pm

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials Inject directly with @HeaderParam Pragmatically via @Context REPLY 8. Dan said: February 2, 2013 at 8:17 pm

Page 7 of 8

Puspendu, Can you upload your source code because that is the exact piece Ive been looking for. I need it in our school for my major project..Thank you.. REPLY 9. Anand said: March 15, 2013 at 6:28 pm Hi, I have gone through this. Its Really usefule for the persons like me who are all new to REST API Now I am working in REST API for file transfer. I am creating one statndlone HTTP Server. I want to transfer the file from REST Client to REST Service. While using your method, I am not able to start my server. I guess through the @FormDataParam.. Because I did not run the application through browser. I have just a java class to run the file transfer process Could you please tell me how to do this? And also the error thrown while starting the server.. the method is not a valid resource method REPLY Puspendu Banerjee said: March 16, 2013 at 12:41 am Can you please share your project/codebase REPLY 10. yassinedz said: March 21, 2013 at 8:48 pm Hi, i am using Apache HTTPClient library and how can i implement a progress bar while file uploading. REPLY Puspendu Banerjee said: May 2, 2013 at 6:55 pm Please bear with me for long delay in reply. I need to understand the architecture of the part where you are trying to implement that progressbar.

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013

RESTFul Webservice: File Upload with Jersey | How To & Tutorials REPLY 11. shantanu said: May 2, 2013 at 6:29 pm Thank you for a wonderful upload! REST is stateless protocol. i am uploading files from different clients i want to send the client id (String) as well as the file contents For such multiple parameters how should i modify your code ? REPLY Puspendu Banerjee said: May 2, 2013 at 6:51 pm It depends on how you are planning to send the Identifier. If you use a field in the form to carry that identifier as follows: <input name="clientId" type="hidden" > You can use the following method signature: public Response uploadFile( @FormDataParam("file") InputStream uploadedInputStream, @FormDataParam("file") FormDataContentDisposition fileDetail, @FormDataParam("clientId") String clientId ) REPLY

Page 8 of 8

Blog at WordPress.com. Theme: Chateau by Ignacio Ricci. Follow

Follow How To & Tutorials


Powered by WordPress.com

http://puspendu.wordpress.com/2012/08/23/restful-webservice-file-upload-with-jersey/

23.05.2013