webuijsf
Tag upload


Use the webuijsf:upload tag to create a component that can be used to browse the local file system for a file, and upload a copy of the file's contents to the web application.

HTML Elements and Layout

The Upload component produces an XHTML <input type="file"> element, which displays a text input field with an adjacent Browse button. The user can type a file name or click the Browse button to select a file. When the form is submitted, the file is uploaded. Note that this tag requires the use of a filter.

Configuring the UploadFilter

In order for the webuijsf:upload tag to work, you must configure the web application to use the com.sun.webui.jsf.util.UploadFilter. Configure the filter by declaring a filter element in the web application's deployment descriptor, web.xml.

 
  <filter>
    <filter-name>UploadFilter</filter-name>
    <filter-class>com.sun.webui.jsf.util.UploadFilter</filter-class>
  </filter>
 

Map the filter to the FacesServlet by adding the following filter mapping in the same file, for example

  <filter-mapping>
    <filter-name>UploadFilter</filter-name>
    <servlet-name>FacesServlet</servlet-name>
  </filter-mapping>
 

The UploadFilter uses the Apache commons fileupload package and woodstock implemented subclasses. The UploadFilterDiskFileUpload class can be configured, as needed, by specifying UploadFilter init parameters. The following parameters are available:

The UploadedFile model object

The contents of the uploaded file, together with some information about it are stored in an instance of com.sun.webui.jsf.model.UploadedFile. Using this object you can get the content of the file as a String or write the contents to disk, as well as get properties such as the name and the size of the file. In the interest of conserving memory, the contents and file data are only available during the HTTP request in which the file was uploaded.

UploadedFile Method Summary
 void dispose()
          Dispose of the resources associated with the file upload (this will happen automatically when the resource is garbage collected).
 java.lang.String getAsString()
          Use this method to retrieve the contents of the file as a String
 byte[] getBytes()
          Use this method to retrieve the contents of the file as an array of bytes.
 java.lang.String getContentType()
          Get the content-type that the browser communicated with the request that included the uploaded file.
 java.io.InputStream getInputStream()
          Returns a InputStream for reading the file.
 java.lang.String getOriginalName()
          Use this method to retrieve the name that the file has on the web application user's local system.
 long getSize()
          The size of the file in bytes
 void write(java.io.File file)
          Write the contents of the uploaded file to a file on the server host.
 

Configuring the webuijsf:upload tag

To access the contents of the uploaded file from the webuijsf:upload tag you have two options:

To optionally specify a label for the component, use the label attribute, or specify a label facet.

Client Side Javascript Functions

In all the functions below, <id> should be the generated id of the Upload component.
field_setDisabled(<id>, <disabled>) Enable/disable the field. Set <disabled> to true to disable the component, or false to enable it.
field_setValue(<id>, <newValue>) Set the value of the field to <newValue>.
field_getValue(<id>) Get the value of the field.
field_getInputElement(<id>) Get hold of a reference to the input element rendered by this component.
component_setVisible(<id>) Hide or show this component.

Examples

Get the contents of the file as a String (using a managed bean)

On the form that controls the upload:

 
<webuijsf:upload id="upload2"
           uploadedFile = "#{FileUploadBean.uploadedFile}"
           label="Choose a file: "
           required="true"/>

On the page that displays the results of the upload:

 
<webuijsf:staticText id="text"
               text ="File contents are bound to string: " >
<webuijsf:staticText id="text"
               text ="#{FileUploadBean.stringContent}"/>

The managed bean looks like this:

 
import java.io.Serializable;
import com.sun.webui.jsf.model.UploadedFile;

public class FileUploadBean implements Serializable {
        
     //
     // Holds value of property uploadedFile.
     //
    transient private UploadedFile uploadedFile;

     //
     // Getter for property stringContent.
     // @return Value of property stringContent.
     //
    public String getStringContent() {
        return uploadedFile.getAsString();
    }

     //
     // Getter for property uploadedFile.
     // @return Value of property uploadedFile.
     //
    public UploadedFile getUploadedFile() {
        return this.uploadedFile;
    }

     //
     // Setter for property uploadedFile.
     // @param uploadedFile New value of property uploadedFile.
     //
    public void setUploadedFile(UploadedFile uploadedFile) {
        this.uploadedFile = uploadedFile;
    }
}

Write the contents of the file to disk (using a ValueChangeListener)

On the form that controls the upload:

 
<webuijsf:upload id="upload1"
           label="Choose a file: "
           valueChangeListener="#{FileUploadedListener.processValueChange}"/>

Code for the ValueChangeListener

import java.io.File; 
import java.io.Serializable;
import javax.faces.event.AbortProcessingException; 
import javax.faces.event.ValueChangeEvent;
import com.sun.webui.jsf.model.UploadedFile;

public class FileUploadedListener implements ValueChangeListener, Serializable {
    
        public void processValueChange(ValueChangeEvent event) 
        throws AbortProcessingException {
        Object value = event.getNewValue(); 
        if(value != null && value instanceof UploadedFile) {
            UploadedFile uploadedFile = (UploadedFile)value;
                     
            String name = uploadedFile.getOriginalName();
            if(name == null || name.length() == 0) {
                name = "tmp.tmp";
            }
            String suffix = name.substring(name.indexOf("."));
            if(suffix.length() == 0) {
                suffix = ".tmp";
            }
            String prefix = name.substring(0, name.indexOf("."));
            try {
                File tmpFile = File.createTempFile(prefix, suffix);
                uploadedFile.write(tmpFile);
            } catch(Exception ex) {
                // report the problem
            }         
        }
    }
}


Tag Information
Tag Classcom.sun.webui.jsf.component.UploadTag
TagExtraInfo ClassNone
Body ContentJSP
Display NameNone

Attributes
NameRequiredRequest-timeTypeDescription
bindingfalsefalsejava.lang.String A ValueExpression that resolves to the UIComponent that corresponds to this tag. This attribute allows the Java bean that contains the UIComponent to manipulate the UIComponent, its properties, and its children.
maxLengthfalsefalsejava.lang.String The maximum number of characters that can be entered for this field.
uploadedFilefalsefalsejava.lang.String

The value of this attribute must be a JSF EL expression, and it must resolve to an object of type com.sun.webui.jsf.model.UploadedFile. See the JavaDoc for this class for details.

converterfalsefalsejava.lang.String The converter attribute is used to specify a method to translate native property values to String and back for this component. The converter attribute value must be one of the following:
  • a JavaServer Faces EL expression that resolves to a backing bean or bean property that implements the javax.faces.converter.Converter interface; or
  • the ID of a registered converter (a String).
requiredfalsefalsejava.lang.String Flag indicating that an input value for this field is mandatory, and failure to provide one will trigger a validation error.
columnsfalsefalsejava.lang.String

Number of character character columns used to render this field. The default is 40.

preservePathfalsefalsejava.lang.String If preservePath is true the upload component will preserve the literal value of the file input element as set by the user on the client.

Different browsers handle the value of an HTML input element of type "file" differently. Some browsers submit the literal value of the input element in the multipart/form-data file portion of the request, others only submit the file name portion and not the directory portion. If this property is set to true, the literal value (typically the full path name either entered explicitly by the user, or from a file selection dialogue) will be stored and submitted in a hidden field. The UploadRenderer will preserve the full file path in the corresponding UploadFilterFileItem instance, encapsulated by the UploadedFile instance. @see com.sun.webui.jsf.model.UploadedFile#getClientFilePath
It is not clear if it is a security risk to transmit the full file path in clear text to the server.
The default value is false.

onDblClickfalsefalsejava.lang.String

Scripting code executed when a mouse double click occurs over this component.

onKeyPressfalsefalsejava.lang.String

Scripting code executed when the user presses and releases a key while the component has focus.

onSelectfalsefalsejava.lang.String

Scripting code executed when some text in this component value is selected.

onFocusfalsefalsejava.lang.String

Scripting code executed when this component receives focus. An element receives focus when the user selects the element by pressing the tab key or clicking the mouse.

renderedfalsefalsejava.lang.String Indicates whether the HTML code for the component should be included in the rendered HTML page. If set to false, the rendered HTML page does not include the HTML for the component. If the component is not rendered, it is also not processed on any subsequent form submission.
idfalsetruejava.lang.StringNo Description
onKeyUpfalsefalsejava.lang.String

Scripting code executed when the user releases a key while the component has focus.

onMouseUpfalsefalsejava.lang.String

Scripting code executed when the user releases a mouse button while the mouse pointer is on the component.

styleClassfalsefalsejava.lang.String

CSS style class(es) to be applied to the outermost HTML element when this component is rendered.

stylefalsefalsejava.lang.String

CSS style(s) to be applied to the outermost HTML element when this component is rendered.

onClickfalsefalsejava.lang.String

Scripting code executed when a mouse click occurs over this component.

onBlurfalsefalsejava.lang.String

Scripting code executed when this element loses focus.

toolTipfalsefalsejava.lang.String

Sets the value of the title attribute for the HTML element. The specified text will display as a tooltip if the mouse cursor hovers over the HTML element.

onMouseDownfalsefalsejava.lang.String

Scripting code executed when the user presses a mouse button while the mouse pointer is on the component.

disabledfalsefalsejava.lang.String

Flag indicating that the user is not permitted to activate this component, and that the component's value will not be submitted with the form.

validatorExpressionfalsefalsejava.lang.String Used to specify a method in a backing bean to validate input to the component. The value must be a JavaServer Faces EL expression that resolves to a public method with return type void. The method must take three parameters:
  • a javax.faces.context.FacesContext
  • a javax.faces.component.UIComponent (the component whose data is to be validated)
  • a java.lang.Object containing the data to be validated.

The backing bean where the method is defined must implement java.io.Serializable or javax.faces.component.StateHolder.

The method is invoked during the Process Validations Phase.

onMouseOutfalsefalsejava.lang.String

Scripting code executed when a mouse out movement occurs over this component.

onMouseOverfalsefalsejava.lang.String

Scripting code executed when the user moves the mouse pointer into the boundary of this component.

onMouseMovefalsefalsejava.lang.String

Scripting code executed when the user moves the mouse pointer while over the component.

htmlTemplatefalsefalsejava.lang.String Alternative HTML template to be used by this component.
immediatefalsefalsejava.lang.String Flag indicating that event handling for this component should be handled immediately (in Apply Request Values phase) rather than waiting until Invoke Application phase.
labelfalsefalsejava.lang.String

If set, a label is rendered adjacent to the component with the value of this attribute as the label text.

onChangefalsefalsejava.lang.String

Scripting code executed when the element value of this component is changed.

visiblefalsefalsejava.lang.String

Use the visible attribute to indicate whether the component should be viewable by the user in the rendered HTML page.

onKeyDownfalsefalsejava.lang.String

Scripting code executed when the user presses down on a key while the component has focus.

labelLevelfalsefalsejava.lang.String

Sets the style level for the generated label, provided the label attribute has been set. Valid values are 1 (largest), 2 and 3 (smallest). The default value is 2.

readOnlyfalsefalsejava.lang.String

Flag indicating that modification of this component by the user is not currently permitted, but that it will be included when the form is submitted.

valueChangeListenerExpressionfalsefalsejava.lang.String Specifies a method to handle a value-change event that is triggered when the user enters data in the input component. The attribute value must be a JavaServer Faces EL expression that resolves to a backing bean method. The method must take a single parameter of type javax.faces.event.ValueChangeEvent, and its return type must be void. The backing bean where the method is defined must implement java.io.Serializable or javax.faces.component.StateHolder.
tabIndexfalsefalsejava.lang.String

Position of this element in the tabbing order of the current document. Tabbing order determines the sequence in which elements receive focus when the tab key is pressed. The value must be an integer between 0 and 32767.


Variables
No Variables Defined.


Output Generated by Tag Library Documentation Generator. Java, JSP, and JavaServer Pages are trademarks or registered trademarks of Sun Microsystems, Inc. in the US and other countries. Copyright 2002-4 Sun Microsystems, Inc. 4150 Network Circle Santa Clara, CA 95054, U.S.A. All Rights Reserved.