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.

61 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.

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

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.

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

Tech Guy 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

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


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

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


Training for IT and Software Courses 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

Training for IT and Software Courses 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

Training for IT and Software Courses 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

Training for IT and Software Courses 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

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

jeni said...


Thank you so much for sharing these amazing tips. I must say you are an incredible writer, I love the way that you describe the things. Please keep sharing. sap training in chennai

sap training in velachery

azure training in chennai

azure training in velachery

cyber security course in chennai

cyber security course in velachery

ethical hacking course in chennai

ethical hacking course in velachery

shiny said...

Thanks for this incredible idea to our computer knowledge.

data science training in chennai

data science training in annanagar

android training in chennai

android training in annanagar

devops training in chennai

devops training in annanagar

artificial intelligence training in chennai

artificial intelligence training in annanagar

Arpita Raj said...

Highly valuable information,looking for more update like this.
Dot Net Training in Chennai
.net coaching centre in Chennai
.Net Training in Chennai
Dot Net Training Online
Dot Net Online course
Dot Net Certification course
Dot Net Training in Velachery

renju raj said...

Informative content,thanks for sharing...waiting for next update.

ibm training in chennai

ibm course in chennai
aix training in chennai
ibm course
ibm training
inplant course in chennai
plc training institute in chennai

vivekvedha said...

Thanks for your valuable post... The data which you have shared is more informative for us...
acte chennai

acte complaints

acte reviews

acte trainer complaints

acte trainer reviews

acte velachery reviews complaints

acte tambaram reviews complaints

acte anna nagar reviews complaints

acte porur reviews complaints

acte omr reviews complaints


Devi said...

I am glad to see your article. Very interesting to read your article.
benefits of artificial intelligence
.net core features
about hadoop
what are the devops tools
selenium interview questions and answers pdf download

siva said...

This article is very interesting to read, it shares useful information for the learners.
web development vs android development
selenium features
best language in the world
ethical hacker
devops interview questions and answers
rpa interview questions

Flora said...

Very informative blog. In this blog, I got so much useful information.
software testing career growth
software testing scope
top languages to learn
use of php in web development
digital marketing interview questions and answers for experienced
hadoop developer interview questions and answers for experienced

Aishwariya said...

Nice work keep it up thanks for sharing the knowledge.Thanks for sharing this type of information, it is so useful. Primavera Training in Chennai | Primavera online course

salome said...

interesting to read
best-angular-training in chennai |

UFABET1688 said...

Hi! I just want to offer you a huge thumbs up for the great info you have got here on this post. I will be returning to your site for more soon. ยูฟ่าสล็อต

SBPwindows said...

Your article is good to understand, are you interested in doors and windows? Our service is helpful to you.
Modern aluminium doors in chennai
Best Aluminium Windows in Chennai
upvc ventilator window in Chennai

Bhuvana said...

Very wonderful informative article. I appreciated looking at your article. Very wonderful reveal. I would like to twit this on my followers. Many thanks! .

AWS Training in Hyderabad

vivikhapnoi said...

Keep up the good work , I read few posts on this web site and I conceive that your blog is very interesting
Vé máy bay Vietnam Airline tu Ha Lan ve Viet Nam

Ve may bay Bamboo tu New Zealand ve Viet Nam

combo trọn gói khách ly khách sạn 14 ngày Hà Nội

dịch vụ xe đưa đón sân bay

xin visa kết hôn Hàn Quốc

phỏng vấn xin visa kết hôn Nhật Bản

Rashi Singh said...

If you want to spend a beautiful time in Uttar Pradesh with the company of hot girls then the Uttar Pradesh Escorts is the best place for you. The agency is very much reputed and has all the facilities to give you all the pleasure you want. So quickly avail of our services and have a time that you will never forget.
Aligarh Escort Service
Bareilly Call Girls
Jhansi Call Girl
Call Girls In Kanpur
Call Girl In Lucknow

Maneesha said...

I am overwhelmed by your post with such a nice topic. Usually I visit your blogs and get updated through the information you include but today’s blog would be the most appreciable. Well done!
cloud computing course in hyderabad

Maneesha said...

Thanks for sharing this information. I really like your blog post very much. You have really shared an informative and interesting blog post with people..
data science training in hyderabad

360DigiTMG said...

They're produced by the very best degree developers who will be distinguished for your polo dress creation. You'll find Ron Lauren inside an exclusive array which includes particular classes for men, women.
data science coaching in hyderabad

Ramesh Sampangi said...

Informative blog and knowledgeable content. Keep sharing more blogs with us. Thanks for sharing with us.
Data Science Training in Hyderabad

The Blogger Worlds2 said...

"WIFI Password Hacker Professional Prank" is a JOKE app. It is WIFI hacking simulator and it only pretends to break into secured WIFI network. Wifi Password Hacker Download

Anonymous said...

Let all of us be united and raise the flag of Pakistan high to celebrate our Independence Day. This is the day to make our country Pakistan special. Quotations For 14 August

Anonymous said...


Wow, amazing post thank you. if you want more tech information click here.

does dd discount take apple pay
picasso app download for pc

Anonymous said...

This blog is really informative. I appreciate you sharing this post with us. Java stands as one of the most popular and powerful programming languages, and mastering it can open doors to endless opportunities in the rapidly evolving tech industry. Enroll in Java training in Solapur to upskill yourself.

Chaitanya said...

Hi there friends, Good paragraph and nice arguments commented at this place, I am really enjoying by these.
Tosca Automation Online Training
Advanced JAVA Online Training
Spring Online Training
<a href="https://viswaonlinetrainings.com/courses/groovy-script-online-training/>Groovy Script Online Training</a>