PrimeFaces Upload File

In PrimceFaces the tag for upload file is p:fileUpload.

This is the xhtml page

<!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:f=”http://java.sun.com/jsf/core”
xmlns:h=”http://java.sun.com/jsf/html”
xmlns:ui=”http://java.sun.com/jsf/facelets”
xmlns:p=”http://primefaces.org/ui”
xmlns:c=”http://java.sun.com/jsp/jstl/core”>
<h:head>
</h:head>
<h:body>
<h:form>
<p:fileUpload
fileUploadListener=”#{fileUploadController.handleFileUpload}”
mode=”advanced” dragDropSupport=”false” update=”messages”
sizeLimit=”100000″ fileLimit=”3″
allowTypes=”/(.|/)(gif|jpe?g|png)$/” />
<p:growl id=”messages” showDetail=”true” />
</h:form>
</h:body>
</html>

The managed bean is:

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;  
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;  
@Component
@ManagedBean
@SessionScoped
public class FileUploadController {
      public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage(“Succesful”, event.getFile().getFileName() + ” is uploaded.”);
        FacesContext.getCurrentInstance().addMessage(null, msg);
        //get uploaded file from the event
        UploadedFile uploadedFile = (UploadedFile)event.getFile();

        //create an InputStream from the uploaded file
        InputStream inputStr = null;
        try {
            inputStr = uploadedFile.getInputstream();
        } catch (IOException e) {
            //log error
        e.printStackTrace();
        }

        //create destination File
        String destPath = “D:\fbm\user\”+event.getFile().getFileName();
        File destFile = new File(destPath);

        //use org.apache.commons.io.FileUtils to copy the File
        try {                  
            FileUtils.copyInputStreamToFile(inputStr, destFile);
        } catch (IOException e) {
            //log error
        e.printStackTrace();
        }
    }
}

 In the web.xml add:

<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>

download this jar:

commons-fileupload
commons-io

this is the output:

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *