In this example, we will learn how to upload a file via Ajax in PrimeFaces.
<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>
@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
Accessing URL: http://localhost:8080/index.xhtml
Clicking on 'Choose' button:
On selecting a file:
Dependencies and Technologies Used: