File upload example in JSF 2

The file upload implementation in Java based web application is very complex and we need to be dependent on Apache fileupload libraries. When we work on JSF(Java Server Faces), we have jsf pages with other inputs along with file inputs, so integration with Apache fileupload libraries make more complex or else we have to dependent on some third party file upload components like primefaces, richfaces etc.

Servlet 3.0 is part of Java EE 6 specification, hence “Part” interface and @MultiPartConfig annotation were introduced for easy way to do the file upload without any third party libraries. So any servlet 3.0 implementation servers like Tomcat 7.x, Jboss 6.x, GlassFish 3.x can get benefit of servlet 3.0 but the file upload feature is not available in JSF 2.1 and again we have to be dependent on servlet to do the file upload in JSF.
Recently JEE 7 specification was released and it’s now very easy to upload the file in JSF 2.2, because file upload component(<h:inputFile/>) was added in this version.

After completion of this example you will be able to see the output in the browser like following:

The home page

file upload example in jsf

When you click on the Upload button without selecting any file
file upload example in jsf

When a file is browsed and selected
file upload example in jsf

Finally when file gets uploaded
file upload example in jsf

We need to do the simple three steps for uploading file in JSF 2.2

Add <h:inputFile> tag in JSF page
Add enctype=”multipart/form-data” attribute in enclosing <h:form> tag
Create the field in managed bean with “Part” data type.

Below example explains file upload function using <h:inputFile> tag    in JSF 2.2.


JDK 1.6
Tomcat Server v7


Input Page: index.xhtml
Managed Bean:
Deployment descriptor: web.xml

Look at the below source codes:

Deployment descriptor – web.xml


View – index.xhtml

This is the jsf page and it has two inputs for uploading two files. You can upload two files at a time or you can upload one file at a time.


Managed Bean –

This is managed bean and it has an action called uploadFile() which gets triggered from the jsf page and uploads the file to the destination.

This file contains all the utility methods used in application. For example, here we have only one method which extracts the file name from the “Part”.

This file holds all the constants used in this application


That’s all. Thanks for your reading. Please do not forget to leave a comment.

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.