October 03, 2009

Easy file upload in Java using Jersey and Uploadify

Uploading a bunch of files to your server. I have come across this particular requirement a few times now during my web development career, but only recently did I discover a very easy way to implement it. And by easy I mean easy on both the client side and the server side.

Server

On the server side we develop our web applications in Java using Glassfish for our deployement server. You can have your standard Servlet class that catches your requests, but recently we bumped into Jersey. And I must say, I really love it. Here is for example the code to accept a file upload request.

@Path("/file")
public class FileHandler {
@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("text/plain")
public String uploadFile(@FormParam("file") File file, @FormParam("file") FormDataContentDisposition fcdsFile) {
String fileLocation = "/files/" + fcdsFile.getFileName();
File destFile = new File(fileLocation);

// your code here to copy file to destFile

return "1";
}
}

That's it. The FormDataContentDisposition is a recent addition to Jersey which allows you to retrieve the name of the file that is being uploaded.

Client

For the client side, I decided to make use of Uploadify. They basically provided a wrapper around SWFUpload using JQuery. Here is the code I used on the client side:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>SimpleFileUpload</title>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery.uploadify.v2.1.0.min.js"></script>
<link rel="stylesheet" href="css/uploadify.css" type="text/css" media="screen"/>

<script type="text/javascript">
$(function() {
$('#file_upload').uploadify({
'uploader' : 'swf/uploadify.swf',
'script' : 'rest/file/upload',
'fileDataName' : 'file',
'cancelImg' : 'img/cancel.png',
'multi' : true
});
});
</script>
</head>
<body>
<h1>Simple File Upload</h1>

<h3>Multiple file upload made easy</h3>

<div id="file_upload"></div>
<br/>
<input type="button" value="Clear Queue" onclick="$('#file_upload').uploadifyClearQueue();"/>
<input type="button" value="Submit Queue" onclick="$('#file_upload').uploadifyUpload();"/>
</body>
</html>

Voila, now you have a simple web application that is able to upload files to your server. You can download a sample application here.

62 comments:

armyofda12mnkeys said...

Curious would this work with a multi-file upload with Uploadify?
Been looking for some easy-to-implement solutions.

Unknown said...

Yes, if you take a look at the code for the client side, you can see that I already used "multi: true". Uploadify will call the method in the FileHandler for each file you upload.

Radhika Bhagavathula said...

I am having problems in using Uploadify to upload files larger than 100MB as per my requirement.
Can I use Jersey for that as I am currently using apache commons fileupload which breaks for large files. also I am not able to download jersey. is there no download access right now? Can I have the software downloaded from a different location? Any help is appreciated.

Unknown said...

Hello Radhika. At the moment it is better to use FormDataParam instead of FormParam when parsing multipart data. And the jersey software should still be available from the same location: Jersey v1.4.

rqualis said...

I think you are missing the web.xml sevlet definition...correct? I didn't see how the client will know what backend java app to call, so I added the servlet def to the web.xml and then the following error came back:
javax.servlet.ServletException: Servlet class: 'com.my.test.FileUploaderJersey' does not implement javax.servlet.Servlet
Maybe I am missing something, but would you know why I got that error based on the info I provided above. Note, in your client, you stated that 'rest/file/upload' is the script uploadify is to use. How do you tie that to the back end?

Unknown said...

The FileHandler class is not a Servlet, it is actually just a class capable of handling REST calls. The actual endpoint is still a servlet of course, but this servlet is provided by Jersey. If you download my sample application (at the end of the post), you can find the web.xml. In there you will see that the ServletAdaptor is configured to listen to all calls to /rest/*. There is also an init parameter that specifies the package in which Jersey will look for classes that are annotated with @Path.

Anonymous said...

I tried the example you posted but it did not work. It does not trigger the annotated Java app, I have the web.xml same as your example. Basically, nothing happens on the backend. I commented out everything and just have a print statement to show that the uploadFile method was called, an I only get back "HTTP Error: 404" -- http://en.wikipedia.org/wiki/HTTP_404. I noticed in your example you did not have a button to select the files. Were you able to test this example?

rqualis said...

By the way, the last post is by me. I did see you web.xml file, but still not able to get ti working.

Unknown said...

- downloaded the sample project
- unzipped it
- opened the project with Netbeans 6.9.1
- resolved a reference problem to the jersey-bundle.jar using jersey-bundle-1.1.5.1.jar
- built the application
- deployed in glassfish: asadmin deploy dist/SimpleFileUpload.war
- pointed browser (firefox) to http://localhost:8080/SimpleFileUpload which showed the following page: screenshot

In other words, for me it worked. Maybe you deploy your the war in a different application server than glassfish?

Anonymous said...

I did it as your steps, and no error report, but nothing happen.it seems that the path 'rest/file/upload' do not work.
I just type some code like System.out.println("......called") in the method uploadNewFile(,), but when I run the code, submit, no strings in the console.
So... thanks in advance!

rqualis said...

Yes I used WebLogic. I like the Jersey technology, but had to do it another way. You Blog was still a good one and thanks for sharing.

Craig Ringer said...

Beware: This example doesn't work well with multi-file uploads if you want to actually submit a form after the uploads are completed. Because Uploadify's uploadifyUpload() method is asynchronous, the form tends to submit before the uploads complete.

More importantly, with Jersey 1.5 there's a new method for handling uploads that lets you accept a stream directly. Here's an example handler class, though it'll be nigh-unreadable because of the horrid comment formatting in Blogger, so I'll reproduce it and some more info here:

http://soapyfrogs.blogspot.com/2011/02/handling-file-uploads-with-java-ee-6.html

@Path("/file")
public class FileHandler {

@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces("text/plain")
public String uploadFile(
@FormDataParam("file") InputStream file,
@FormDataParam("file") FormDataContentDisposition fileInfo) {

// your code here to copy file to destFile
System.err.println("Received file: " + fileInfo.getFileName() + " as " + file);

return "1";
}

}

Anonymous said...

Is possible to use JSF context (FacesContext) in Jersey context ? i have tried, but is null. Any idea ? Because i must get a bean from JSF context

Craig Ringer said...

"Anonymous": AFAIK, JAX-RS/Jersey doesn't offer any direct access to the JSF context. However, if you're using CDI/Weld then JAX-RS beans share the same session scope, etc, and you can inject JSF beans into a JAX-RS resource class easily.

Alternately, you could store your bean references as session properties on the HttpSession, which you can access via the HttpServletRequest in both JAX-RS and in JSF. In JSF, get it via FacesContext.getExternalContext().In JAX-RS, add a new method parameter to your REST methods: "@Context HttpServletRequest request".

Gee, wouldn't it be nice to have some interface consistency in the Java world! CDI is helping a bit, and Seam Solder should make some more difference once it's stable and supported on all application servers, but for now we get to learn different ways to do different things in different parts of the Java EE stack.

Wright Petter said...

Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.
I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging.
If anyone wants to become a Java developer learn from Java EE Online Training from India.
or learn thru Java EE Online Training from India .
Nowadays Java has tons of job opportunities on various vertical industry.

priya said...


Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.
Data Science Training in Indira nagar
Data Science Training in btm layout
Data Science Training in Kalyan nagar
Data Science training in Indira nagar
Data Science Training in Marathahalli
Data science training in bangalore

Soumitasai said...

Nice Article… I love to read your articles because your writing style is too good, its is very very helpful for all of us and I never get bored while reading your article because, they are becomes a more and more interesting from the starting lines until the end.

Check out : big data training in velachery
big data hadoop training cost in chennai
big data training in chennai omr
big data training in chennai velachery

IT Tutorials said...

Really useful information. Thank you so much for sharing.It will help everyone.Keep Post. RPA training in chennai | RPA training in Chennai with placement | UiPath training in Chennai | UiPath certification in Chennai with cost

Gowri said...

Really Happy to say your post is very interesting. Keep sharing your information regularly for my future reference. Thanks Again.

Check Out:
big data training in chennai chennai tamil nadu
big data training in velachery
big data hadoop training in velachery

Diya shree said...

Good job and thanks for sharing such a good blog You’re doing a great job. Keep it up !!

PMP Certification Fees | Best PMP Training in Chennai |
pmp certification cost in chennai | PMP Certification Training Institutes in Velachery |
pmp certification courses and books | PMP Certification requirements |
PMP Training Centers in Chennai | PMP Certification Requirements | PMP Interview Questions and Answers

Jagadeesh said...

Thanks for sharing info about Java.
Learn Digital Academy offers, Digital marketing courses in Bangalore.
In-class training program, practically on Live Projects.

Kayal said...

Nice post! I love this blog and I got more kinds of techniques in this topic. Thanks for your sharing.

Primavera Training in Chennai
Primavera Course in Chennai
Pega Training in Chennai
Unix Training in Chennai
Tableau Training in Chennai
Power BI Training in Chennai
Excel Training in Chennai
Oracle Training in Chennai
Social Media Marketing Courses in Chennai

kavithasathish said...

A good blog for the people who really needs information about this.
Good work keep it up.
TOEFL Coaching in Chennai
TOEFL Classes in Chennai
German Language Classes in Chennai
IELTS Training in Chennai
Japanese Language Course in Chennai
spanish language course in chennai
TOEFL Coaching in Porur
TOEFL Coaching in Adyar

Gowri said...

Thanks for sharing such a Wonderful blog. This is such a exact information i am been searching for. Keep post

Check Out:
react js tutorial
it courses in chennai
react js classes near me

Gowri said...


Thanks for sharing such a Wonderful blog. This is such a exact information i am been searching for. Keep post

Check Out:
Selenium course fees in chennai
Best Selenium training in chennai
Selenium training courses in chennai

IT Tutorials said...



Get the most advanced AWS Course by Professional expert. Just attend a FREE Demo session.
For further details call us @ 9884412301 | 9600112302
AWS training in chennai | AWS training in velachery

Tech Guy said...

For Data Science training in Bangalore, Visit:
Data Science training in Bangalore

Anonymous said...

For Data Science training in Bangalore, Visit:
Data Science training in Bangalore

Lovable vicky said...


Nice information, want to know about Selenium Training In Chennai
Selenium Training In Chennai
Data Science Training In Chennai
Protractor Training in Chennai
jmeter training in chennai
Rpa Training Chennai
Rpa Course Chennai
Selenium Training institute In Chennai
Python Training In Chennai

Lovable vicky said...


Rpa Training in Chennai
Rpa Course in Chennai
Blue prism training in Chennai

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Course In Chennai

Rajesh said...

Nice infromation
Selenium Training In Chennai
Selenium course in chennai
Selenium Training
Selenium Training institute In Chennai
Best Selenium Training in chennai
Selenium Training In Chennai

Rajesh said...

Rpa Training in Chennai
Rpa Course in Chennai
Rpa training institute in Chennai
Best Rpa Course in Chennai
uipath Training in Chennai
Blue prism training in Chennai

Data Science Training In Chennai
Data Science Course In Chennai
Data Science Training institute In Chennai
Best Data Science Training In Chennai


Python Training In Chennai
Python course In Chennai
Protractor Training in Chennai
jmeter training in chennai
Loadrunner training in chennai

vijay said...

Thanks for your valuable post... The data which you have shared is more informative for us...
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore

Durai Moorthy said...

Nice blog, thanks for sharing. Please Update more blog about this, this is really informative for me as well
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore

python training in vijayawada said...

We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

GlobalEmployees said...

Find my blog post here
web designer
salesforce developer
laravel developer
web developer

Rajesh Anbu said...

Very Nice Blog. Thanks for sharing such a nice Blog.
aws Training in Bangalore
python Training in Bangalore
hadoop Training in Bangalore
angular js Training in Bangalore
bigdata analytics Training in Bangalore
python Training in Bangalore
aws Training in Bangalore


sociogramics said...

You are so cool! I don't think I've truly read through anything like that before. So wonderful to find someone with a few genuine thoughts on this topic. Seriously.. thank you for starting this up. This site is one thing that is required on the internet, someone with a little originality!
Tech info

offpageseo70 said...

Nice blog,I understood the topic very clearly,And want to study more like this.
Data Scientist Course

Unknown said...

Hi, your article was of great help. I loved the way you shared the information, thanks.
Amazing article, I highly appreciate your efforts, it was highly helpful. Thank you CEH Training ,CEH Certification, CEH Online Course, Ethicalhacking

Unknown said...

Hi this is the nice blog, thanks for sharing us
Get Azure, azure training,azure certification,microsoft azure training,azure course,azure online training

Unknown said...

Hi, This is a great article. Loved your efforts on it buddy. Thanks for sharing this with us.
Get cissp
it training courses.
CISSP training ,cissp exam cost, CISSP certification. .Get VMware, vmware training.,vmware course., vmware online training., vmware interview questions and answers.,vmware Certification. .AWS, aws training,aws course,aws certification training,aws online training
Get PMP pmp certification, pmp training,pmp certification in gurgaon,pmp certification cost,pmp training certification

Mr Frudo said...

read at hercampus also Click Here

ravali said...

This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

data science course

CloudLearn ERP said...

You have written a very informative article with great quality content and well laid out points. I agree with you on many of your views and you've got me thinking.
Best Data Science training in Mumbai

Data Science training in Mumbai


akshaya said...

I can feel the great dedication in you when I read this post. I wonder how a writer could be more diligent in creating each and every word of the blog. Web Designing Course Training in Chennai | Web Designing Course Training in annanagar | Web Designing Course Training in omr | Web Designing Course Training in porur | Web Designing Course Training in tambaram | Web Designing Course Training in velachery

BestTrainingKolkata said...

I have to agree with the valid points you make in your article because I see things like you. Additionally, your content is interesting and really good reading material. Thank you for sharing your talent.
SAP training in Kolkata
Best SAP training in Kolkata
SAP training institute in Kolkata

BestTrainingMumbai said...

This material makes for great reading. It's full of useful information that's interesting,well-presented and easy to understand. I like articles that are well done.
SAP training in Mumbai
Best SAP training in Mumbai
SAP training institute Mumbai

nisha said...

Nice Blog. the blog is really very Impressive.

Data Science Training Course In Chennai | Data Science Training Course In Anna Nagar | Data Science Training Course In OMR | Data Science Training Course In Porur | Data Science Training Course In Tambaram | Data Science Training Course In Velachery



Anirban Ghosh said...

I like your article Your take on this topic is well-written and original. I would never have thought of this.
SAP training in Kolkata
SAP training Kolkata
Best SAP training in Kolkata
SAP course in Kolkata
SAP training institute Kolkata


pratheep said...

Excellent Blog!!! Such an interesting blog with clear vision, this will definitely help for beginner to make them update.

Robotic Process Automation (RPA) Training in Chennai | Robotic Process Automation (RPA) Training in anna nagar | Robotic Process Automation (RPA) Training in omr | Robotic Process Automation (RPA) Training in porur | Robotic Process Automation (RPA) Training in tambaram | Robotic Process Automation (RPA) Training in velachery

Customer relationship management said...

Wow it is really wonderful and awesome thus it is very much useful for me to understand many concepts and helped me a lot.

oracle certification Online Training in bangalore

oracle certification courses in bangalore

oracle certification classes in bangalore

oracle certification Online Training institute in bangalore

oracle certification course syllabus

best oracle certification Online Training

oracle certification Online Training centers

Customer relationship management said...

I recently came across your article and have been reading along. I want to express my admiration of your writing skill and ability to make readers read from the beginning to the end. I would like to read newer posts and to share my thoughts with you.

Blue Prism training in bangalore

Blue Prism class in bangalore

learn Blue Prism in bangalore

places to learn Blue Prism in bangalore

Blue Prism schools in bangalore

Blue Prism reviews in bangalore

Blue Prism training reviews in bangalore

Blue Prism training in bangalore

Blue Prism institutes in bangalore

Blue Prism trainers in bangalore

learning Blue Prism in bangalore

where to learn Blue Prism in bangalore

best places to learn Blue Prism in bangalore

top places to learn Blue Prism in bangalore

Blue Prism training in bangalore india

Customer relationship management said...

Such a very useful article. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article.

WebSphere MQ Online Training

WebSphere MQ Classes Online

WebSphere MQ Training Online

Online WebSphere MQ Course

WebSphere MQ Course Online

Customer relationship management said...

Very interesting blog Thank you for sharing such a nice and interesting blog and really very helpful article.

Machine Learning Online Training

Machine Learning Classes Online

Machine Learning Training Online

Online Machine Learning Course

Machine Learning Course Online

Ishu Sathya said...

Read your blog, Excellent content written on "Easy file upload in Java using Jersey and Uploadify"
If you are looking for RPA related job with unexpected Pay, then visit below link

RPA Training in Chennai
RPA course in Chennai
RPA course
RPA Training in Velachery
RPA Training
Robotic Process Automation Training
Robotic Process Automation Training in Chennai
Robotic Process Automation Courses
RPA Classes in Chennai
Robotic Process Automation Certification

nisharoshan said...

Really it as an awesome article...very interesting to read..You have provided an nice article....Thanks for sharing.

Web Designing Training Course in Chennai | Certification | Online Training Course | Web Designing Training Course in Bangalore | Certification | Online Training Course | Web Designing Training Course in Hyderabad | Certification | Online Training Course | Web Designing Training Course in Coimbatore | Certification | Online Training Course | Web Designing Training Course in Online | Certification | Online Training Course

priyash said...

Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
Correlation vs Covariance
Simple linear regression
data science interview questions

Jayalakshmi said...

Thanks for your informative article, Your post helped me to understand the future and career prospects & Keep on updating your blog with such awesome article.
oracle training in chennai

oracle training in tambaram

oracle dba training in chennai

oracle dba training in tambaram

ccna training in chennai

ccna training in tambaram

seo training in chennai

seo training in tambaram

praveen said...

Hi nice blog with new information,
Thanks to share with us and keep more updates,

web designing training in chennai

web designing training in porur

digital marketing training in chennai

digital marketing training in porur

rpa training in chennai

rpa training in porur

tally training in chennai

tally training in porur


EXCELR said...

Thanks for sharing nice information data science training Hyderabad

Sathish said...

Thank you for sharing this very useful
Data science Training in bangalore
Aws Training In Bangalore
Hadoop Training In Bangalore
Devops Training In Bangalore
Iot Training in Bangalore