ONJava.com -- The Independent Source for Enterprise Java
oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Upload Files with JSF and MyFaces
Pages: 1, 2, 3, 4, 5, 6

The faces-config.xml File

The JSF configuration file defines the backing bean in the request scope and specifies a navigation rule:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE faces-config PUBLIC
    "-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN"





The MyResult.jsp Page

This web page displays some information about the uploaded file and the hash value:

<%@ taglib uri="http://java.sun.com/jsf/core" prefix="f"%>
<%@ taglib uri="http://java.sun.com/jsf/html" prefix="h"%>


    <h:panelGrid columns="2" border="0" cellspacing="5">

        <h:outputText value="FileName:"/>
        <h:outputText value="#{myBean.myFile.name}"/>

        <h:outputText value="FileSize:"/>
        <h:outputText value="#{myBean.myFile.size}"/>

        <h:outputText value="Param:"/>
        <h:outputText value="#{myBean.myParam}"/>

        <h:outputText value="Result:"/>
        <h:outputText value="#{myBean.myResult}"/>



The displayed file name may actually contain the full path in the client's file system, as provided by the web browser:

The output produced by the result page
Figure 2. The output produced by the result page


There are many cases when users need to upload files through their browsers, but there is no ideal way for handling these files on the server side. Keeping the files' content in memory is acceptable only for small files, while storing the uploaded content in temporary files complicates the situation. MyFaces lets you choose the solution that is good for your application, but this framework has some minor problems. It doesn't let you delete the temporary files when you don't need them anymore, the file names are sometimes file paths, and there are no warnings when users attempt to upload files that are too large. These can be fixed, since the source code is available, and this article indicates where you can improve the code of MyFaces. For many applications, however, you might find MyFaces usable without any changes. The samples of this article have been tested with JSF 1.1.01, MyFaces 1.0.9, and Commons File Upload 1.0.


Andrei Cioroianu is the founder of Devsphere and an author of many Java articles published by ONJava, JavaWorld, and Java Developer's Journal.

JavaServer Faces

Related Reading

JavaServer Faces
By Hans Bergsten

Return to ONJava.com.