Wednesday, March 19, 2014

Primefaces fileUploadListener not working

Add the following dependency in your pom.xml
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>

Add this in your web.xml

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

<filter>
  <filter-name>PrimeFaces FileUpload Filter</filter-name>
  <filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>

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

In h:form it's important to write enctype="multipart/form-data"

ajax="false" for the command button is necessary

Example Using Simple File Upload

<?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:f="http://java.sun.com/jsf/core"
      xmlns:p="http://primefaces.org/ui"
      >
    <h:head>
    <h:outputStylesheet library="css" name="table-style.css"  />
    </h:head>
 
    <h:body>
<h:form enctype="multipart/form-data">
<p:panel>
<p:messages showDetail="true"/>
<p:fileUpload value="#{fileUploadBean.file}" mode="simple" />
<p:commandButton value="Submit" ajax="false" actionListener="#{fileUploadBean.upload}"/>
</p:panel>
</h:form>
</h:body>

</html>

Bean:
package com.malware;

import java.io.Serializable;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;

import org.primefaces.context.RequestContext;
import org.primefaces.model.UploadedFile;

@ManagedBean
@SessionScoped
public class FileUploadBean implements Serializable{

private static final long serialVersionUID = 3998498873477818990L;

private UploadedFile file;

public void init(){
}
    public UploadedFile getFile() {
        return file;
    }

    public void setFile(UploadedFile file) {
        this.file = file;
    }
 
    public void upload() {
        if(file != null) {        
            FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Successfully Uploaded File " , file.getFileName());
            FacesContext.getCurrentInstance().addMessage(null, msg);
        }
    }
}

1 comment:

  1. I made everything but still doesn't work.. I don't know why

    ReplyDelete