FileUpload 2.x - roberts-sandbox/test-wiki-page-title GitHub Wiki

TOCSTART

TOCEND

The FileUpload component allows adding the single and multiple file upload capability to your applications.

Declaring the File Upload Filter

If you aren't using Servlet-3.0 to make FileUpload components to work, the following filter should be registered in application's web.xml file:

  <filter>
    <filter-name>ResourceFilter</filter-name>
    <filter-class>org.openfaces.util.ResourceFilter</filter-class>
  </filter>

<filter-mapping> <filter-name>ResourceFilter</filter-name> <servlet-name>Faces Servlet</servlet-name> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>

Note that, if you are using OpenFaces 2.0, you will need this ResourceFilter anyway.

There are also some optional application context parameters, which are related to various aspects of functionality of all FileUpload components used in the application. See the Storing Uploaded Files and Restricting the Maximum File Size sections below.

General Usage

The file upload component lets the user upload file(s) on server There are two file upload components available: for single file upload - <o:singleFileUpload> and for multiple file upload - <o:multipleFileUpload>. These components have a lot in common, so if it is not explicitly said that they have differences, they, eventually, haven't.

Here's a very basic example of how <o:singleFileUpload> component can be used.

<o:singleFileUpload completionListener="#{FileUploadBean.uploadComplete}"
                  render="uploadedFilesSummary"
                  acceptedFileTypes="jpg png bmp jpeg gif"
                  acceptedMimeTypes="image/*"
/>

<h:outputText id="uploadedFilesSummary" value="#{FileUploadBean.uploadedFilesSummary}"/>

And here's the appropriate portion of the session-scoped FileUploadBean class.

    private List<FileUploadItem> uploadedFiles = new ArrayList<FileUploadItem>();
<span class="code-keyword">public</span> void uploadComplete(UploadCompletionEvent e) {
    uploadedFiles.addAll(e.getFiles());
}

<span class="code-keyword">public</span> <span class="code-object">String</span> getUploadedFilesSummary() {
    <span class="code-keyword">if</span> (uploadedFiles == <span class="code-keyword">null</span>) <span
        class="code-keyword">return</span> <span class="code-quote">"No files uploaded"</span>;
    <span class="code-object">int</span> totalUploadedSize = 0;
    <span class="code-keyword">for</span> (FileUploadItem uploadedFile : uploadedFiles) {
        File file = uploadedFile.getFile();
        <span class="code-keyword">if</span> (file != <span class="code-keyword">null</span>)
            totalUploadedSize += file.length();
    }
    <span class="code-keyword">return</span> uploadedFiles.size() + <span class="code-quote">" file(s) uploaded with a total length of "</span> + (totalUploadedSize / 1024) + <span
        class="code-quote">"Kb"</span>;
}

Here's how it works.

The <o:singleFileUpload> tag adds the SingleFileUpload component itself. The completionListener attribute specifies the binding expression for an event listener method which will be invoked when upload completes. This method receives a parameter of type UploadCompletionEvent, and it contains the full information about each uploaded file (upload status, file name, and file content), see the Handling the Upload Completion Event section below.

In essence, the <o:singleFileUpload> tag declaration with completionListener attribute is enough to add the file upload capability to your application.

It is a quite common scenario to update some portions of the page in response to upload completion though, to reflect the status or content of the uploaded files. To support this scenario, the FileUpload component have the attribute render, which re-render components when upload completes.
The example above shows how to use this attribute to update the page with Ajax to reflect the uploaded files.

To allow to add files only with right extension the acceptedFileTypes attribute is used. You can specify file's extensions for which upload is allowed. To simplify for user to find FileUpload component's supported extensions in file dialog window, the acceptedMimeTypes attribute is used.

Note that acceptedMimeTypes attribute is supported for only HTML5-supported browsers.
Storing Uploaded Files

All of the uploaded files are stored in the temporary directory, whose location can optionally be customized with the org.openfaces.fileUpload.tempDir application context parameter in application's web.xml file. By default, the standard Java temporary directory is used, as defined by the java.io.tmpdir system property.

Here's an example of changing the upload directory to c:/tempUploadDir.

  <context-param>
    <param-name>org.openfaces.fileUpload.tempDir</param-name>
    <param-value>c:/tempUploadDir</param-value>
  </context-param>

When file upload completes, it gives references to the newly uploaded files stored in the temporary directory via the completionListener method described above. It is possible that the file with the same name as the newly uploaded one already exists in the temporary directory. In this case the FileUpload component stores the file under a modified unique file name with the same extension, and still provides the original file name through the upload completion event parameter, as described in the section below.

Handling the Upload Completion Event

As noted above, the event upload completion listener receives one parameter of type UploadCompletionEvent.

The main method of interest in this class is the List<FileUploadItem> getFiles() method, which returns a list of FileUploadItem instances, that specify all of the details about each uploaded file. Each FileUploadItem instance in this list has the following methods.

Method Description
String getFileName() Returns the original file name as it was named on the client's machine prior to downloading, without the file path. Note that it might differ from the name of the file stored in the upload directory, because the file might be renamed there to avoid name collisions, as described in the section above.
File getFile() Returns a reference to the uploaded file stored in the temporary upload directory, or null if upload was terminated or failed. See also the upload status description below.
FileUploadStatus getStatus() Returns an enumeration-typed value which defines the upload status of this file. There are three such statuses:
  • FileUploadStatus.SUCCESSFUL – the file has been uploaded successfully, and is available in the upload directory;
  • FileUploadStatus.STOPPED – file upload has been terminated by the user (no file is stored in the upload directory);
  • FileUploadStatus.FAILED – file upload has terminated due to any input/output error (no file is stored in the upload directory).
  • FileUploadStatus.SIZE_LIMIT_EXCEEDED – file upload has terminated because file's size is bigger than specified(as a context parameter in the web.xml or through attribute fileSizeLimit). |

Note that when the upload completion listener method is invoked, the uploaded files are stored in the temporary directory as noted above. It is up to the application how to handle these files from this moment – the application can either intentionally retain the files there, read them, or copy to a different location, and/or remove files from the temporary directory. The FileUpload component does not automatically remove these files from this directory.

Restricting the Maximum File Size

By default, the size of the files which can be uploaded with FileUpload component is not limited. To limit the size of files to some value, you can specify FileUpload component's attribute fileSizeLimit or the org.openfaces.fileUpload.fileSizeLimit application context parameter in the web.xml file. In both cases, value should be specified in kilobytes.

Here's an example which specifies a maximum size of file as 10000Kb(or roughly 10Mb) for all FileUpload components through application context parameter in the web.xml, except FileUpload component with id="multipleFileUpload" - for it maximum size of file is specified as 30000Kb(or roughly 30Mb)

  <context-param>
    <param-name>org.openfaces.fileUpload.fileSizeLimit</param-name>
    <param-value>10000</param-value>
  </context-param>
 <o:multipleFileUpload id="multipleFileUpload" fileSizeLimit="30000"
            completionListener="#{FileUploadBean.uploadComplete}" />
Note that due to the technical limitations of FileUpload being a pure HTML component, without using any browser plug-ins, checking the size of file against file size limit is not a byte-to-byte strict checking, and there can be a checking error of up to 1Kb.
Additional Customizations

Here are some additional attributes for customizing component's functionality:

Attribute Description
autoUpload Specifying the value of true for this attribute will make the files to be uploaded automatically as they are being added to the component with the "Add..." button. This attribute is only applicable for the multiple upload mode, where this functionality is turned off by default. The FileUpload component in the single upload mode always uploads the file as the user has chosen the file from the "File Open" dialog.
disabled Specifying the value of true for this attribute disables an ability to select and upload files.
tabindex Similar to the other components, which can receive focus, specifies the integer value defining the focus traversal order.

Single File Upload structure

The <o:singleFileUpload> tag allows to change structure of component with the following attributes:

Customization Structure Attribute Description
layoutMode Defines whether single file upload component should show full information about upload or should be compact.
browseButtonDuringUpload This attribute defines what is happening to browseButton while file is uploading. You can set values: hide, disable or showStop.
stopButtonNearProgress This attribute defines if stop icon will be displayed near progress while file is uploading.
showInfoAfterUpload This flag defines what appearance component will has after upload complete - should it show information about file upload or it should return to the first state.

Appearance Customization

Here are the attributes that can be set for <o:singleFileUpload> and <o:multipleFileUpload> tags, which you can use to change style of the various parts of these FileUpload components.

Customization Attribute Description
style/styleClass The in-place style declaration/CSS class name for the entire FileUpload component. Things like width, border and background for the entire FileUpload component can typically be customized here.
fileNameStyle/fileNameClass Style for the file name text.
statusStyle/statusClass Style for the upload status text.

Here is an additional list for <o:multipleFileUpload> tag.

Customization Attribute Description
headerStyle/headerClass The style for the header area in the FileUpload component – the top-most row where the "Add" and "Upload" buttons are shown.
rowStyle/rowClass The style for each file upload row, which corresponds to each added, or uploaded file.

If you'd like to customize the texts displayed in the FileUpload component's buttons, you can specify text's values in attributes: browseButtonText, stopButtonText
As <o:multipleFileUpload> tag also has buttons "Upload", "Remove All", "Stop All", "Remove", "Clear", attributes to specify the text is also provided.

To perform more detailed button customizations (e.g. specify their individual tab indexes, etc.), you can specify your own <h:commandButton> declarations for each respective button, in the appropriate facet of the FileUpload component. Also, if you want to customize appearance of progressBar, you can specify <o:progressBar> declaration in the facet progressBar.

Here's a list of such facets.

Facet Name Description
browseButton The "Browse" button (in case of using <o:singleFileUpload> tag) or The "Upload" (<o:multipleFileUpload> tag) which is displayed on the left.
stopButton The "Stop" button, which allows terminating file upload while it is in progress.

Additional facets for <o:multipleFileUpload> tag.

Facet Name Description
uploadButton The "Upload" button, which is displayed on the right in a multiple upload mode.
clearButton The "Clear" button, which removes an appropriate file entry for an already uploaded file.
removeButton The "Remove" button, which allows removing a file before it was uploaded.
removeAllButton The "Remove All" button, which is displayed at the bottom of the component in the multiple upload mode, to clear all file entries.
stopAllButton The "Stop All" button stopping all uploading of all files, which is displayed at the bottom of the component in the multiple upload mode while files are uploading.

It is also possible to customize all kinds of texts displayed by the FileUpload component using the following attributes.

Attribute Description
fileSizeLimitErrorText The message that is displayed when the file exceeds the maximum allowed file size (as configured in the application).
notUploadedStatusText The upload status text displayed at the right of the progress bar when the upload for an appropriate file has not been started yet.
inProgressStatusText The upload status text displayed at the right of the progress bar when the appropriate file is being uploaded.
stoppedStatusText The upload status text displayed at the right of the progress bar when the upload for an appropriate file has been terminated by the user.
uploadedStatusText The upload status text displayed at the right of the progress bar when the upload for an appropriate file has finished successfully.
wrongFileTypeText When user adds file with not appropriate extension(which you specified in acceptedFileTypes attribute, onwrongfiletype event is fired. By default, alert popup with the text. This attribute allows to change this text.
directoryDroppedText Only for HTML5-supported browsers. When user adds folder as an file , the ondirectorydropped event is fired. By default, alert popup with the text. This attribute allows to change this text.

The <o:multipleFileUpload> tag has uploadModewhich allows you to specify mode how several files will be uploaded: parallel or sequential.

Note that you can specify to show useful information (such as size of file) for status with attributes: inProgressStatusText, stoppedStatusText, uploadedStatusText.
Here is FileUpload component which shows size and current uploaded size(only when upload in progress) of file in KB:
<o:multipleFileUpload id="multipleFileUpload"
                          inProgressStatusText="{uploaded} / {size} KB[KB]"
                          uploadedStatusText="{size} KB[KB]"
                          fileSizeLimitErrorText="{size} [KB] KB is too big"
           />
Adding file(s) with drag and drop feature.

This feature is allow users to add files by dragging from out of browser (For example: file manager or desktop). It is supported only for browsers, which fully support HTML5 File API such as Chrome and Firefox. FileUpload component is provide drop target area inside component but if you need it somewhere else, component allows to specify external drop target area instead of default one. You can customize drop target area appearance with the following attributes.

Attribute Description
dropTargetStyle/dropTargetClass A style for dropTarget.
dropTargetDragoverStyle/dropTargetDragoverClass A dragover style for drop target.
dropTargetText The drop target text displayed.
externalDropTarget Define an id of element which will be used as dropTarget for this component instead of built-in component's drop target.
External browse button feature.

Additional externalBrowseButton string attribute refers to a user-defined Browse button by its id, so that when that button is clicked, the appropriate file upload component's Browse dialog is shown. If this attribute is specified, then the built-in Browse button of the File Upload component itself is not shown.

Show in popup feature.

Can be added by showInPopup boolean attribute which specifies whether the upload progress with a related information should be shown in-place in an upload component itself, or in a separate pop-up window. When this attribute is set to true, the upload component itself will only display a browse button (unless external browse button is specified), and the reset is displayed in a pop-up window.

When the showInPopup attribute is shown to true, it is possible to control the popup's alignment by adding the <o:position> tag into the <o:singleFileUpload> or <o:multipleFileUpload> tag. This tag will have the following attributes:

  • by – a reference to a component by which the popup should be aligned. This attribute is optional and the default reference component is a browse button.
  • horizontalAlignment, verticalAlignment, horizontalDistance, verticalDistance – specify how the file upload popup will be aligned relative to the reference component, specified by the "by" attribute.

If you'd like to customize Close button you can specify text's value in the attribute cloaseButtonText or specify declaration in the closeButton facet.

Client-Side Events

The FileUpload component supports a set of standard client-side events such as onblur, onchange, onclick, oncontextmenu, ondblclick, onkeyup, onkeydown, onkeypress, onfocus, onmousedown, onmouseover, onmouseup, onmouseout, onmousemove.

In addition, it supports the following FileUpload specific client-side events:

Event attribute name Description
onstart Occurs when upload (single or multiple) starts. You can get files from event: e.files or e.file - depends on FileUpload tag you are using: <o:multipleFileUpload> or <o:singleFileUpload>
onend Occurs when upload for all files (or one, in case of a single file upload) completes. You can get files from event: e.files or e.file - depends on FileUpload tag you are using: <o:multipleFileUpload> or <o:singleFileUpload>
onfilestart Occurs when file upload(for current one) starts. You can get the current file from event: e.file
onfileinprogress Occurs when progress of file upload changes. You can get the current file from event: e.file
onfileend Occurs when file upload(for current one) completes. You can get the current file from event: e.file
onwrongfiletype Occurs when user is trying to add file with not appropriate extension(which you specified in acceptedFileTypes attribute.
ondirectorydropped Only for HTML5-supported browsers - occurs when the user is trying to drop folder in drop target for files.
Note that, if you want to remove default behavior for onwrongfiletype and ondirectorydropped events, your handler function should return false.

Such events as onstart, onend, onfilestart, onfileinprogress and onfileend are provide information about file(s).
If you are using <o:multipleFileUpload> tag, to get files from onstart and onend events, refer to e.files instead of e.file

<script type="text/javascript">
      function fileUploaded(e){
        var file = e.file;
        alert("File :" + file.getName() + " has size:" + file.getSize());
      }
  function allFilesUploaded(e) {
    <span class="code-keyword">var</span> files = e.files;
    <span class="code-keyword">var</span> result = "";
    <span class="code-keyword">for</span> (<span class="code-keyword">var</span> i = 0; i &amp;lt; files.length; i++) {
      <span class="code-keyword">var</span> file = files[i];
      result += <span class="code-quote">"File :"</span> + file.getName() + <span
        class="code-quote">" has size:"</span> + file.getSize() + <span class="code-quote">"\n"</span>;
    }
    alert(result);
  }

</script> <o:multipleFileUpload completionListener="#{FileUploadBean.uploadComplete}" onfileend="fileUploaded(event)" onend="allFilesUploaded(event)" />

Client-Side API

Client-Side API for single FileUpload

There is a only one method for single FileUpload component: getFile() which returns a current File object.

Client-Side API for multiple FileUpload

All client-side API methods for the <o:multipleFileUpload> tag are listed in the following table:

Method Description
getFiles() Returns an array of File's object.
uploadAllFiles() Uploads all added files, which are not uploaded yet.
removeAllFiles() Removes all files and their information windows. Make sure, that there is no files which upload is in progress.
stopAllUploads() Stops all files which are uploading now.

The client side File object has the following methods:

File object method Description
getName() Returns the name of the file.
getStatus() Returns the upload status of the file.
getSize() Returns the size of the file.
getProgress() Returns the upload progress of the file.
remove() Removes the file and it's information window if it's upload not in progress. This method can be applied to the file in case if it's already uploaded or it's not started upload yet.
stopUpload() Stops the upload of file.
⚠️ **GitHub.com Fallback** ⚠️