File Upload in JSF PrimeFaces 5.2 example simple & advanced mode

In this tutorial, let us see how to upload files from client to server using JSF PrimeFaces. PrimeFaces is JSF front-end framework. One of the UI component in Primefaces is <p:fileupload>  that is used to upload files. In Primefaces, file upload has been simplified.

In this example, let us design a form to accept Name and uploading of Photos & Resume.

Technologies used in the project

JSF 2.2
PrimeFaces 5.2
Eclipse IDE
Maven 3.3
Java 1.8
Tomcat

Jars related to FileUpload

commons-fileupload-1.2.2.jar
commons-io-2.0.1.jar
primefaces-5.2.jar

Jars Related to JSF

javax.faces.jar (JSF 2.2 (Mojarra 2.2.0))

Project Structure:

JSF PrimeFaces File Upload Project Structure

Now let us see the steps to develop fileupload application using JSF Primefaces.

1. Create a Dynamic WebProject in Eclipse (JSFPrimeFacesFileUpload)

2. Create web page (fileupload.xhtml) to accept Name and files (Photos and Resume) using component tags.

The JSF code is given below

fileUpload.xhtml


<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>JSF PrimeFaces File Upload Example</title>
</h:head>
<h:body>
		<h3>JSF  PrimeFaces 5.2  File Upload Example</h3>
<h:form id="fileUpoad" prependId="false" 	enctype="multipart/form-data">

			<h:outputLabel for="txtIdName" value="Enter Your Name:" />
			<p:inputText id="txtIdName" required="true" value="#{fileUploadBean.name}"	label="Name" />

              <p:separator/>

<!-- File Upload with  mode="advanced". multiple files can be uploaded. upload button  -->		

			<h:outputLabel for="fileIdPhoto" value="Upload Your Photo:" />

			<p:fileUpload id="fileIdPhoto"  fileUploadListener="#{fileUploadBean.uploadPhoto}" mode="advanced" dragDropSupport="false"
			 multiple="true" update="messages" sizeLimit="10000000" fileLimit="3" allowTypes="/(\.|\/)(gif|jpe?g|zip)$/"  />

			  <p:messages id="messages" autoUpdate="true" closable="true" />

              <p:separator/>

	<!-- File Upload with  mode="simple". Only one file can be uploaded. upload using submit button -->		  

			<h:outputLabel for="fileIdResume" value="Upload Your Resume:" />

			<p:fileUpload id="fileIdResume"  value="#{fileUploadBean.resume}" mode="simple" skinSimple="true" description="Resume"/>

  		<p:separator/>			

    		<p:commandButton value="Submit" ajax="false" action="#{fileUploadBean.uploadResume}"/>   

</h:form>									

</h:body>
</html> 

In the view page, we have created two file upload components. One is created with advanced mode for uploading photos and another one is created with simple mode for uploading Resume.

File upload component created with advanced mode uses jQuery/Ajax to upload file.

Some of the attributes used in fileupload component with advanced mode in this example

multiple – Allows to upload multiple files. Default value is false
update – To mention client side id of the component () to be updated after file upload completes.
fileUploadListner – To listen file upload events
sizeLimit – Maximum file size (in Bytes) to be allowed. Default is unlimited.
fileLimit – No of attempts for uploading files.
dragDropSupport – Supports drag and drop of files to be uploaded. Browser should be compatible to support this feature. Default value is false
allowTypes – list of types to be allowed for uploading.

For more attributes of fileupload components, please visit http://www.primefaces.org/docs/vdl/3.4/index.html?primefaces-p/fileUpload.html

The above form’s encryption type is set to “multipart/form-data” which encodes form data when submit the form.

3. Now let us create managed bean for uploading files.

FileUploadBean.java

package net.javaonline.jsf.primefaces.fileupload.controller;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;
import org.apache.commons.io.FilenameUtils;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name="fileUploadBean")
@RequestScoped

public class FileUploadBean implements Serializable{

/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	private String name;
	private UploadedFile resume;

	public UploadedFile getResume() {
		return resume;
	}

	public void setResume(UploadedFile resume) {
		this.resume = resume;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String uploadResume() throws IOException{

		UploadedFile uploadedPhoto=getResume();
		//System.out.println("Name " + getName());
		//System.out.println("tmp directory" System.getProperty("java.io.tmpdir"));
		//System.out.println("File Name " + uploadedPhoto.getFileName());
		//System.out.println("Size " + uploadedPhoto.getSize());
		String filePath="c:/temp/kk/";
        byte[] bytes=null;

            if (null!=uploadedPhoto) {
                bytes = uploadedPhoto.getContents();
                String filename = FilenameUtils.getName(uploadedPhoto.getFileName());
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+filename)));
                stream.write(bytes);
                stream.close();
            }

        return "success";
	}

	/* 	The above code is for file upload using simple mode. */

	//This below code is for file upload with advanced mode.

	public void uploadPhoto(FileUploadEvent e) throws IOException{

		UploadedFile uploadedPhoto=e.getFile();

		String filePath="c:/temp/kk/";
        byte[] bytes=null;

            if (null!=uploadedPhoto) {
                bytes = uploadedPhoto.getContents();
                String filename = FilenameUtils.getName(uploadedPhoto.getFileName());
                BufferedOutputStream stream = new BufferedOutputStream(new FileOutputStream(new File(filePath+filename)));
                stream.write(bytes);
                stream.close();
            }

        FacesContext.getCurrentInstance().addMessage("messages",new FacesMessage(FacesMessage.SEVERITY_INFO,"Your Photo (File Name "+ uploadedPhoto.getFileName()+ " with size "+ uploadedPhoto.getSize()+ ")  Uploaded Successfully", ""));
	}

} 

4. Create a web page (fileUploadAck.xhtml) for displaying resume upload successful message.

fileUploadAck.xhtml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui">

    <h:head>
    	<title>JSF 2.2 Resume Upload Acknowledgement </title>
    </h:head>
    <h:body bgcolor="white">

    	<h2>Hello Mr. #{fileUploadBean.name} Your Resume has been Successfully Uploaded</h2>

    </h:body>
</html> 

4. web.xml: Now Map the javax.faces.webapp.FacesServlet instance in web.xml. Latest version of PrimeFaces does not require any filter class (org.primefaces.webapp.filter.FileUploadFilter) for uploading files. But if you want to set thresholdSize and uploadDirectory, you can put the filter class in web.xml and configure the below parameters using init-param

thresholdSize – Maximum memory to be used for keeping bytes of file. If the file size exceeds this limit, it is written to disk

uploadDirectory – disk path to keep temporary files that exceeds threshold size. Default path in windows : C:\Users\username\AppData\Local\Temp\ (i.e System.getProperty(“java.io.tmpdir”));

The complete web.xml


<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JSF_Example</display-name>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
  <context-param>
    <description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
    <param-name>javax.faces.STATE_SAVING_METHOD</param-name>
    <param-value>client</param-value>
  </context-param>
  <context-param>
    <param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
    <param-value>resources.application</param-value>
  </context-param>
 <context-param>
    <param-name>javax.faces.PROJECT_STAGE</param-name>
    <param-value>Development</param-value>
  </context-param>

<context-param>
  <param-name>primefaces.UPLOADER</param-name>
  <param-value>native</param-value>
</context-param>  

<filter>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
   <init-param>
    <param-name>thresholdSize</param-name>
    <param-value>51200</param-value>
  </init-param>
  <init-param>
    <param-name>uploadDirectory</param-name>
    <param-value>C:\temp\vkj</param-value>
  </init-param>
</filter>

<filter-mapping>
 <filter-name>PrimeFaces FileUpload Filter</filter-name>
 <servlet-name>Faces Servlet</servlet-name>
</filter-mapping>

  <listener>
    <listener-class>com.sun.faces.config.ConfigureListener</listener-class>
  </listener>
</web-app>

6. Create application configuration resource file (faces-config.xml) for providing navigation rule.

faces-config.xml


<?xml version="1.0" encoding="UTF-8"?>
<faces-config
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
    version="2.2">

<application>
	  <resource-bundle>
		<base-name>JSF Primefaces File Upload</base-name>
		<var>labels</var>
	   </resource-bundle>
     </application>

    <navigation-rule>
      <from-view-id>fileUpload.xhtml</from-view-id>
     <navigation-case>
		<from-action>#{fileUploadBean.uploadResume}</from-action>
		<from-outcome>success</from-outcome>
		<to-view-id>FileUploadAck.xhtml</to-view-id>
	</navigation-case>
     </navigation-rule>

 </faces-config>

Note : Ensure that you have created c:\temp\kk to keeep the uploaded files.

Run the project by calling

http://localhost:8080/JSFPrimeFacesFileUpload/faces/fileUpload.xhtml

fileupload fileupload1 fileupload2 fileuploadack

 

 

Reference : Primefaces File Upload

Download JSFPrimeFacesFileUpload application  with source code and Jars at 

Leave a Reply