HTML and CSS Reference
In-Depth Information
File Upload
Finally, after almost ten years of no standard file upload component in JSF, the <h:inputFile /> component was
introduced by JSF 2.2. Prior to JSF 2.2 the developer would have to develop his own file upload component or use
component libraries such as RichFaces or PrimeFaces. As an added bonus in JSF 2.2, the file upload component also
supports file upload in Ajax requests.
Using the component is fairly simple. Include the <h:inputFile /> tag inside a form with the enctype set to
multipart/form-data ”. Set the value attribute of the <h:inputFile /> to an object of type javax.servlet.http.Part .
Upon submitting the form, the file selected by the user is transferred to the server and a reference to the file is
available in the Part object through the getInputStream() method. You can add validation to the file upload using
the validator attribute on the <h:inputFile /> tag. In the validator you can check the file size, content type, file
name, file contents, and any other header sent along with the file in the request. To upload a file in an Ajax request,
simply add the <f:ajax /> tag to the <h:commandButton /> submitting the form.
As an example, Listing 5-28 shows a form containing the inputFile component. The example uses Ajax to upload
the file by including the f:ajax component inside the commandButton that initiates the upload.
Listing 5-28. Form for Uploading a Photo into a Managed Bean
<h:form id="frm-photo-upload" enctype="multipart/form-data" >
<h:outputLabel for="photo" value="Please select your photo and click Upload Photo" />
<h:inputFile id="photo" value="#{myProfile.photo}" validator="#{myProfile.validatePhoto}" />
<h:commandButton value="Upload Photo" action="#{myProfile.uploadPhoto}">
<!-- Remove the f:ajax tag for plain old file upload -->
<f:ajax execute="photo" render="@all" />
</h:commandButton>
<h:messages />
</h:form>
Listing 5-29 is the managed bean for the upload form. It contains methods for validating that the file upload is an
image and below 2 MB in size as well as an upload method where the contents of the file uploaded is extracted using
the IOUtils class from the Apache Commons IO project. 1
Listing 5-29. Managed Bean Receiving and Processing the File Upload
import java.io.IOException;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.servlet.http.Part;
import org.apache.commons.io.IOUtils;
@ManagedBean
@RequestScoped
public class MyProfile {
@EJB private UserProfileService userProfileService;
private UserProfile userProfile;
private Part photo;
1 The Apache Commons IO project is a collection of libraries for working with IO functionality. The project can be found at
this URL: http://commons.apache.org/proper/commons-io/
 
Search WWH ::




Custom Search