Tuesday, January 28, 2014

JSF 2.2 Native FileUpload

It took so many time that many have wondered if there would be the day when JSF had native file upload support. Well, the day has finally come. The scenario became to be set when JavaEE 6 brought Multipart support in the Servlets 3.0 specification. Now, in JavaEE 7 with Servlets 3.1 and JSF 2.2 we finally have the <h:inputFile> component.

(If you care to analyse the source code, FacesServlet in the Mojarra implementation of JSF is annotated with @MultipartConfig)

The JSF file upload implementation is quite simple, and the prerequisites are just two:
  1. Your <h:form>'s enctype attribute must be set to "multipart/form-data".
  2. Your <h:inputFile>'s value attribute must point to a bean property of type javax.servlet.http.Part.
Controller code for JFile Upload

Facelet code with <h:inputFile>

Sample application with upload running on Glassfish 4