Wednesday, June 29, 2011

File uploads with PrimeFaces v2.2.1

I've been working on a few Java EE 6 applications using JSF 2.0 for a while now, and my experience with the default implementation within Glassfish 3.1 - Mojarra has left me wanting for more. One of my applications required a file upload widget. This is doable in Mojarra but requires a shim. I decided to create a spike implementation using PrimeFaces, since that apparently had a fileUpload component; the spike obviously being used to estimate the time I would require to port the application to PrimeFaces.

A few minutes later, and I managed to get a working example up and running. The example is based on several similar examples posted on the internet. I've attempted to document a couple of gotchas encountered.

The Source Code

This was my JSF page; it is quite simple. The fileUpload component was made available on adding the primefaces tag. Note the use of the h:head tag. Apparently, PrimeFaces will add scripts and stylesheet resources with the target value set to "head". If one uses the plain head tag from the xhtml namespace, then the scripts and stylesheets will not be added.



One can notice similarities between the above facelet and the one posted on the AMIS blog, which was followed during the spike.

The managed bean that processes the FileUploadEvent is quite simple. My current need of the hour was to extract the contents of the uploaded file into a byte array to persist into a BLOB in a database; this was duly supported by the UploadedFile class of PrimeFaces.



And finally, to top it off, here are the contents of the deployment descriptor and the resource bundle.





Deployment

PrimeFaces 2.2.1 depends on Commons FileUpload 1.2.1 and Commons IO 1.4 to provide the file upload functionality; one can find the details of the dependencies in the packaged pom.xml of the PrimeFaces distribution. Anyone using Maven will quite obviously not have to bother about this, but for those who do not, it is quite obvious that the files commons-fileupload-1.2.1.jar, commons-io-1.4.jar and primefaces-2.2.1.jar have to be placed in the WEB-INF/lib directory of the packaged WAR file, in case these are not provided by the container.