Close

PrimeFaces - File upload via Ajax

[Last Updated: Jul 28, 2017]

In this example, we will learn how to upload a file via Ajax in PrimeFaces.

JSF page

src/main/webapp/index.xhtml

<h:body style="margin-left:30px">
    <h2>PrimeFaces File Upload Example</h2>
    <h:form>
        <p:fileUpload update="content" auto="true" style="width:500px;"
                      fileUploadListener="#{fileUploadBean.handleUpload}"/>

        <p:panel id="content" style="border:none;">
            <p:outputPanel rendered="#{fileUploadBean.fileName ne null}">
                <h4>File name:</h4>
                #{fileUploadBean.fileName}
                <h4>File content:</h4>
                #{fileUploadBean.fileContent}
            </p:outputPanel>
        </p:panel>
    </h:form>
</h:body>

The manage bean

@ManagedBean
@ViewScoped
public class FileUploadBean {
    private String fileContent;
    private String fileName;

    public void handleUpload(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        byte[] contents = file.getContents();
        fileContent = new String(contents);
        fileName = file.getFileName();
    }

    public String getFileContent() {
        return fileContent;
    }

    public String getFileName() {
        return fileName;
    }
}

To try examples, run embedded tomcat (configured in pom.xml of example project below):

mvn tomcat7:run-war

Output

Accessing URL: http://localhost:8080/index.xhtml

Clicking on 'Choose' button:

On selecting a file:

Example Project

Dependencies and Technologies Used:

  • primefaces 6.1 primefaces
  • jsf-api 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • jsf-impl 2.2.14: This is the master POM file for Oracle's Implementation of the JSF 2.2 Specification.
  • JDK 1.8
  • Maven 3.3.9

PrimeFaces File Upload Example Select All Download
  • file-upload
    • src
      • main
        • java
          • com
            • logicbig
              • example
        • webapp
          • index.xhtml

    See Also