rich:fileUpload fileUpload

Component identification parameters

Name | Value
--- | ---
component-type | org.richfaces.component.FileUpload
component-class | org.richfaces.component.html.HtmlFileUpload
component-family | org.richfaces.component.FileUpload
renderer-type | org.richfaces.renderkit.html.FileUploadRenderer
tag-class | org.richfaces.taglib.FileUploadTag

## Creating the Component with a Page Tag

To create the simplest variant on a page use the following syntax:

Example:

    ...
    <rich:fileUpload />
    ...

## Creating the Component Dynamically Using Java

Example:

    import org.richfaces.component.html.HtmlFileUpload;
    ...
    HtmlFileUpload myFileUpload = new HtmlFileUpload();
    ...

## Details of Usage

The <rich:fileUpload> component consists of two parts:

- List of files which contains the list of currently chosen files to upload with possibility to manage every file

- Component controls - the bar with controls for managing the whole component

There are two places where the uploaded files are stored:

- In the temporary folder (depends on OS) if the value of the `createTempFile` parameter in Ajax4jsf Filter (in web.xml) section is "true" (by Default)

      ...
      <init-param>
              <param-name>createTempFiles</param-name>
              <param-value>true</param-value>
      </init-param>
      ...

- In the RAM if the value of the `createTempFile` parameter in Ajax4jsf Filter section is "false". This is a better way for storing small-sized files.

The "uploadData" attribute defines the collection of files uploaded. See the example below.

Example:

    ...
    <rich:fileUpload uploadData="#{bean.data}"/>
    ...

The "fileUploadedListener" is called at server side after every file uploaded and used for the saving files from temporary folder or RAM.

Example:

    ...
    <rich:fileUpload uploadData="#{bean.data}" fileUploadListener="#{bean.listener}"/>
     ...

The following methods for processing the uploaded files are available:

- `isMultiUpload()`. It returns "true" if several files have been uploaded

- `getUploadItems()`. It returns the list of the uploaded files. If one file was uploaded, the `getUploadItems()` method will return the list consisting of one file

- `getUploadItem()`. It returns the whole list in case of uploading one file only. If several files were uploaded, the `getUploadItem()` method will return the first element of the uploaded files list.

Automatically files uploading could be performed by means of the "immediateUpload" attribute. If the value of this attribute is "true" files are uploaded automatically once they have been added into the list. All next files in the list are uploaded automatically one by one. If you cancel uploading process next files aren't started to upload till you press the "Upload" button or clear the list.

Example:

    ...
    <rich:fileUpload uploadData="#{bean.data}" fileUploadListener="#{bean.listener}" immediateUpload="true"/>
     ...

The "autoclear" attribute is used to remove automatically files from the list after upload completed. See the simple example below.

Example:

    ...
    <rich:fileUpload uploadData="#{bean.data}" autoclear="true"/>
    ...

Each file in list waiting for upload has link "Cancel" opposite its name. Clicking this link invokes JS API `remove()` function, which gets `$('id').component.entries[i]` as a parameter and removes the particular file from list and from the queue for upload. After a file has been uploaded the link "Cancel" changes to "Clear". Clicking "Clear" invokes `clear()` JS API function, which also gets ID of the particular entry and removes it from the list. Uploaded to server file itself is kept untouched.

The <rich:fileUpload> component provides following restrictions:

- On file types, use "acceptedTypes" attribute to define file types accepted by component. In the example below only files with "html" and "jpg" extensions are accepted to upload.

  Example:

      ...
      <rich:fileUpload acceptedTypes="html, jpg"/>
      ...

- On file size, use the `maxRequestSize` parameter(value in bytes) inside Ajax4jsf Filter section in web.xml:

      ...
      <init-param>
              <param-name>maxRequestSize</param-name>
              <param-value>1000000</param-value>
      </init-param>
      ...

- On max files quantity, use the "maxFilesQuantity" attribute to define max number of files allowed to be uploaded. After a number of files in the list equals to the value of this attribute "Add" button is disabled and nothing could be uploaded even if you clear the whole list. In order to upload files again you should rerender the component. As it could be seen in the example below, only 2 files are accepted for uploading.

  Example:

      ...
      <rich:fileUpload maxFilesQuantity="2"/>
       ...

  This is the result:

  <rich:fileUpload> with "maxFilesQuantity" attribute

The <rich:fileUpload> component provides a number of specific event attributes:

- The "onadd" a event handler called on an add file operation

- The "onupload" which gives you a possibility to cancel the upload at client side

- The "onuploadcomplete" which is called after all files from the list are uploaded

- The "onuploadcanceled" which is called after upload has been canceled via cancel control

- The "onerror" which is called if the file upload was interrupted according to any errors

The <rich:fileUpload> component has an embedded Flash module that adds extra functionality to the component. The module is enabled with "allowFlash" attribute set to "true".

These are the additional features that the Flash module provides:

- Multiple files choosing;

- Permitted file types are specified in the "Open File" dialog window;

- A number of additional entry object properties are also available, which can be found RichFaces Developer Guide section on object properties.

Apart from uploading files to the sever without using AJAX, the Flash module provides a number of useful API functions that can be used to obtain information about the uploaded file.

There are 2 ways to obtain the data stored in the FileUploadEntry object.

- By means of JavaScript on the client side. Use the following syntax for that `entries[i].propertyName`. For example `entries[0].state` will return the state of the file the is being processed or has just been processed.

- The properties of `FileUploadEntry` object can be retrieved using the `entry.propertyName` expression in the specific event attributes. For example, `onupload="alert(event.memo.entry.fileName);"` will display a message with the name of the file at the very moment when upload operation starts. A full list of properties can be found in RichFaces Developer Guide section on properties and their attributes.

The given bellow code sample demonstrates how the properties can be used. Please study it carefully.

    ...
                <head>
                      <script>
                            function _onaddHandler (e) {
                                 var i = 0;
                                 for (; i < e.memo.entries.lenght; i++) {
                                       alert(e.memo.entries[i].creator);  //Shows creators of the added files
                                 }
                            }

                            function _onerrorhandle(e) {
                                 alert(e.memo.entry.fileName + "file was not uploaded due  transfer error");
                            }
                      </script>
                </head>
     ...

Moreover, embedded Flash module provides a smoother representation of progress bar during the uploading process: the polling is performed is not by AJAX, but my means of the flash module.

Uploading using Flash module <rich:fileUpload>

However, the Flash module doens't perform any visual representation of the component.

In order to customize the information regarding the ongoing process you could use "label" facet with the following macrosubstitution:

- `{B}`, `{KB}`, `{MB}` contains the size of file uploaded in bytes, kilobytes, megabytes respectively

- `{_B}`, `{_KB}`, `{_MB}` contains the remain file size to upload in bytes, kilobytes, megabytes respectively

- `{ss}`, `{mm}`, `{hh}` contains elapsed time in seconds, minutes and hours respectively

Example:

    ...
    <rich:fileUpload uploadData="#{bean.data}" fileUploadListener="#{bean.listener}">
            <f:facet name="label">
                    <h:outputText value="{_KB}KB from {KB}KB uploaded --- {mm}:{ss}" />
            </f:facet>
    </rich:fileUpload>
    ...

This is the result:

<rich:fileUpload> with "label" facet

You could define labels of the component controls with the help of "addControlLabel" , "clearAllControlLabel" , "clearControlLabel" , "stopEntryControlLabel" , "uploadControlLabel" attributes. See the following example.

Example:

    ...
    <rich:fileUpload addControlLabel="Add file..." clearAllControlLabel="Clear all" clearControlLabel="Clear"
                            stopEntryControlLabel="Stop process" uploadControlLabel="Upload file"/>
    ...

This is the result:

<rich:fileUpload> with labels

The <rich:fileUpload> component allows to use sizes attributes:

- "listHeight" attribute specify height for list of files in pixels

- "listWidth" attribute specify width for list of files in pixels

In order to disable the whole component you could use the "disabled" attribute. See the following example.

Example:

    ...
    <rich:fileUpload disabled="true"/>
    ...

This is the result:

<rich:fileUpload> with "disabled" attribute

It's possible to handle events for fileUpload using JavaScript code. A simplest example of usage JavaScript API is placed below:

Example:

    ...
    <rich:fileUpload  id="upload" disabled="false"/>
    <h:commandButton onclick="${rich:component('upload')}.disable();" value="Disable" />
    ...

<rich:fileUpload> component also provides a number of JavaScript property, that can be used to process uploaded files, file states etc. The given below example illustrates how the `entries[0].state` property can be used to get access to the file state. Full list of JavaScript properties can be found below.

    ...
    <rich:fileUpload fileUploadListener="#{fileUploadBean.listener}"
            maxFilesQuantity="#{fileUploadBean.uploadsAvailable}"
            id="upload"
            immediateUpload="#{fileUploadBean.autoUpload}"
            acceptedTypes="jpg, gif, png, bmp">
                <a4j:support event="onuploadcomplete" reRender="info"  />
    </rich:fileUpload>
    <h:commandButton onclick="if($('j_id232:upload').component.entries[0].state == FileUploadEntry.UPLOAD_SUCCESS) alert ('DONE');" value="Check file state"/>
    ...

The <rich:fileUpload> component allows to use internationalization method to redefine and localize the labels. You could use application resource bundle and define `RICH_FILE_UPLOAD_CANCEL_LABEL`, `RICH_FILE_UPLOAD_STOP_LABEL`, `RICH_FILE_UPLOAD_ADD_LABEL`, `RICH_FILE_UPLOAD_UPLOAD_LABEL`, `RICH_FILE_UPLOAD_CLEAR_LABEL`, `RICH_FILE_UPLOAD_CLEAR_ALL_LABEL`, `RICH_FILE_UPLOAD_PROGRESS_LABEL`, `RICH_FILE_UPLOAD_SIZE_ERROR_LABLE`, `RICH_FILE_UPLOAD_TRANSFER_ERROR_LABLE`, `RICH_FILE_UPLOAD_ENTRY_STOP_LABEL`, `RICH_FILE_UPLOAD_ENTRY_CLEAR_LABEL`, `RICH_FILE_UPLOAD_ENTRY_CANCEL_LABEL` there.

The <rich:fileUpload> component could work together with Seam framework. On RichFaces LiveDemo page you can see how to configure filter for this framework in web.xml file in order to handle <rich:fileUpload> requests.

To make <rich:fileUpload> component work properly with MyFaces extensions, the order in which filters are defined and mapped in web.xml, is important. See corresponding FAQ chapter.

## JavaScript API

JavaScript API

Function | Description
--- | ---
beforeSubmit() | Sets up necessary request parameters for file uploading and submits form to server by command button. This method should be used together with commands.
clear() | Removes all files from the list. The function can also get the `$('id').component.entries[i]` as a parameter to remove a particular file.
disable() | Disables the component
enable() | Enables the component
remove() | Cancels the request for uploading a file by removing this file from upload list and upload queue. Gets `$('id').component.entries[i]` as a parameter.
stop() | Stops the uploading process
submitForm() | Submits form to server. All added files will be put to model and event.

Client side object properties

Property | Description
--- | ---
entries | Returns a array of all files in the list
entries.length | Returns the number of files in the list
entries[i].fileName | Returns the file name, that is retrieved by the array index
entries[i].state | Returns the file state. Possible states are "initialized" - the file is added, corresponds to FileUploadEntry.INITIALIZED constant "progress" - the file is being uploaded, corresponds to FileUploadEntry.UPLOAD_IN_PROGRESS constant "ready" - uploading is in process, corresponds to FileUploadEntry.READY constant The file will be uploaded on queue order. "canceled" - uploading of the file is canceled, corresponds to FileUploadEntry.UPLOAD_CANCELED constant "done" - the file is uploaded successfully, corresponds to FileUploadEntry.UPLOAD_SUCCESS constant "transfer_error" - a file transfer error occurred, corresponds to FileUploadEntry.UPLOAD_TRANSFER_ERROR constant "size_error" - the file exceeded maximum size, corresponds to FileUploadEntry.UPLOAD_SIZE_ERROR constant
entries[i].size | Returns the size of the file. Available in flash enabled version only
entries[i].Type | Returns the mime type of the file. Available in flash enabled version only
entries[i].creator | Returns the name of the author of the file. Available in flash enabled version only
entries[i].creationDate | Returns the date when the file was created. Available in flash enabled version only
entries[i].modificationDate | Returns the date of the last file modification. Available in flash enabled version only

Client side object properties available with specific event attributes

Property | Description
--- | ---
entry.state | Returns the file state. Possible states are "initialized" - the file is added, corresponds to FileUploadEntry.INITIALIZED constant "progress" - the file is being uploaded, corresponds to FileUploadEntry.UPLOAD_IN_PROGRESS constant "ready" - uploading is in process, corresponds to FileUploadEntry.READY constant The file will be uploaded on queue order. "canceled" - uploading of the file is canceled, corresponds to FileUploadEntry.UPLOAD_CANCELED constant "done" - the file is uploaded successfully, corresponds to FileUploadEntry.UPLOAD_SUCCESS constant "transfer_error" - a file transfer error occurred, corresponds to FileUploadEntry.UPLOAD_TRANSFER_ERROR constant "size_error" - the file exceeded maximum size, corresponds to FileUploadEntry.UPLOAD_SIZE_ERROR constant
entry.fileName | Returns the file's name. This property works with all event handlers except for "onadd".
entry.size | Returns the size of the file. Available in flash enabled version only
entry.Type | Returns the mime type of the file. Available in flash enabled version only
entry.creator | Returns the name of the author of the file. Available in flash enabled version only
entry.creationDate | Returns the date when the file was created. Available in flash enabled version only
entry.modificationDate | Returns the date of the last file modification. Available in flash enabled version only

## Facets

Facets

Facet name | Description
--- | ---
label | Defines the information regarding the ongoing process
progress | Defines the information regarding the uploading process

## Look-and-Feel Customization

For skinnability implementation, the components use a style class redefinition method. Default style classes are mapped on skin parameters.

There are two ways to redefine the appearance of all <rich:fileUpload> components at once:

- Redefine the corresponding skin parameters

- Add to your style sheets style classes used by a <rich:fileUpload> component

## Skin Parameters Redefinition

Skin parameters redefinition for a component

Skin parameters | CSS properties
--- | ---
tableBackgroundColor | background-color
tableBorderColor | border-color

Skin parameters redefinition for a font

Skin parameters | CSS properties
--- | ---
generalFamilyFont | font-family
generalSizeFont | font-size

Skin parameters redefinition for a toolbar

Skin parameters | CSS properties
--- | ---
additionalBackgroundColor | background-color
tableBorderColor | border-bottom-color
tableBackgroundColor | border-top-color
tableBackgroundColor | border-left-color

Skin parameters redefinition for items in the list

Skin parameters | CSS properties
--- | ---
tableBorderColor | border-bottom-color

Skin parameters redefinition for a "Cancel", "Clear" links

Skin parameters | CSS properties
--- | ---
generalLinkColor | color

Skin parameters redefinition for a button

Skin parameters | CSS properties
--- | ---
trimColor | background-color

Skin parameters redefinition for a button border

Skin parameters | CSS properties
--- | ---
tableBorderColor | border-color

Skin parameters redefinition for a highlighted button

Skin parameters | CSS properties
--- | ---
trimColor | background-color
selectControlColor | border-color

Skin parameters redefinition for a pressed button

Skin parameters | CSS properties
--- | ---
selectControlColor | border-color
additionalBackgroundColor | background-color

Skin parameters redefinition for "Upload", "Clean" buttons

Skin parameters | CSS properties
--- | ---
generalTextColor | color

Skin parameters redefinition for a disabled "Start" button icon

Skin parameters | CSS properties
--- | ---
tableBorderColor | color

Skin parameters redefinition for a disabled "Clear" button icon

Skin parameters | CSS properties
--- | ---
tableBorderColor | color

## Definition of Custom Style Classes

The following picture illustrates how CSS classes define styles for component elements.

Classes names

Classes names

Classes names that define a component representation

Class name | Description
--- | ---
rich-fileupload-list-decor | Defines styles for a wrapper <div> element of a fileUpload
rich-fileupload-font | Defines styles for a font of buttons and items
rich-fileupload-toolbar-decor | Defines styles for a toolbar
rich-fileupload-list-overflow | Defines styles for a list of files

Classes names that define buttons representation

Class name | Description
--- | ---
rich-fileupload-button | Defines styles for a buttons
rich-fileupload-button-border | Defines styles for a border of buttons
rich-fileupload-button-light | Defines styles for a highlight of button
rich-fileupload-button-press | Defines styles for a pressed button
rich-fileupload-button-dis | Defines styles for a disabled button
rich-fileupload-button-selection | Defines styles for "Upload", "Clean" buttons

Classes names that define the representation of the buttons' icons

Class name | Description
--- | ---
rich-fileupload-ico | Defines styles for an icon
rich-fileupload-ico-add | Defines styles for a "Add" button icon
rich-fileupload-ico-start | Defines styles for a "Upload" button icon
rich-fileupload-ico-stop | Defines styles for a "Stop" button icon
rich-fileupload-ico-clear | Defines styles for a "Clear" button icon
rich-fileupload-ico-add-dis | Defines styles for a disabled "Add" button icon
rich-fileupload-ico-start-dis | Defines styles for a disabled "Upload" button icon
rich-fileupload-ico-clear-dis | Defines styles for a disabled "Clear" button icon

Classes names that define list items representation

Class name | Description
--- | ---
rich-fileupload-table-td | Defines styles for a wrapper <td> element of a list items
rich-fileupload-anc | Defines styles for "Cancel", "Stop", "Clear" links

In order to redefine styles for all <rich:fileUpload> components on a page using CSS, it's enough to create classes with the same names (possible classes could be found in the tables above) and define necessary properties in them.

Example:

    ...
    .rich-fileupload-anc{
        font-weight:bold;
        text-decoration:none;
    }
    ...

This is the result:

Redefinition styles with predefined classes

In the example above the font weight and text decoration for "Cancel" and "Clear" links are changed.

Also it's possible to change styles of particular <rich:fileUpload> component. In this case you should create own style classes and use them in the corresponding <rich:fileUpload> styleClass attributes. An example is placed below:

Example:

    ...
    .myClass{
            font-weight:bold;
    }
    ...

The "addButtonClass" attribute for <rich:fileUpload> is defined as it's shown in the example below:

Example:

    <rich:fileUpload ... addButtonClass="myClass"/>

This is the result:

Redefinition styles with own classes and styleClass attributes

As it could be seen on the picture above, the font style for "Add" button is changed.

## Relevant Resources Links

On RichFaces LiveDemo page you can see an example of <rich:fileUpload> usage and sources for the given example.