Fileupload mit Richfaces 

This article shows the usage of a tomahawk-fileupload with richfaces and facelets. The result is a upload-formular where the upload-button is disabled until the user select a file. All this can be done without any line self hacked javascript-code 🙂

The upload-button depends on a bean-property ‚uploadedFilename‘ which is sync via AJAX.

So it is possible to enabled the upload-button before the file is really uploaded to the server.
We have a jsf-bean:

public class FileUploadBean  {

  private UploadedFile uploadedFile;
  private String uploadedFilename;

  // ... setter and getter ...

  public void uploadFile(final ActionEvent event) {
    if (null != this.uploadedFile) {
      LOG.debug("file-size '"+this.uploadedFile.getSize()+"'");
    }
  }
}

and the facelets-page:

<ui:component
  xmlns:h="http://java.sun.com/jsf/html"
  xmlns:c="http://java.sun.com/jstl/core"
  xmlns:ui="http://java.sun.com/jsf/facelets"
  xmlns:rich="http://richfaces.org/rich"
  xmlns:t="http://myfaces.apache.org/tomahawk"
  xmlns:a4j="http://richfaces.org/a4j">

<c:set var="controlId" value="controls" />

<a4j:form>
  <a4j:jsFunction name="updateFilename" reRender="#{controlId}">
   <a4j:actionparam name="filename" assignTo="#{FileUploadBean.uploadedFilename}" />
  </a4j:jsFunction>
</a4j:form>

<h:form enctype="multipart/form-data">
 <t:inputFileUpload id="fileupload"
                    size="40"
                    value="#{FileUploadBean.uploadedFile}"
                    storage="file"
                    required="true"
                    onchange="updateFilename(this.value)"/>

 <h:panelGroup id="#{controlId}">
   <c:choose>
     <c:when test="#{!empty FileUploadBean.uploadedFilename}">
       <!-- User has selected a File - enable Upload-Control -->
       <h:commandLink value="Upload enabled ..."
                      actionListener="#{FileUploadBean.uploadFile}"/>
     </c:when>
     <c:otherwise>
       <!-- User doenst have selected a File - DISABLE Upload-Control -->
       <h:outputText value="Upload disabled"/>
     </c:otherwise>
   </c:choose>
 </h:panelGroup>
</h:form>

</ui:component>