Monday Sep 02

Key Concepts

File upload with Primefaces

PDFPrintE-mail
Wednesday, 16 May 2012 14:51
AddThis Social Bookmark Button

JavaServer Faces 2 File Upload with Primefaces

Uploading file with Primefaces

The FileUpload component in Primefaces is an HTML5 solution to upload files on server site.

It has two modes, "simple" fileUpload uses native browser upload and "advanced" mode features dragdrop from operating system, progress bar, multi file uploads, upload cancelling, size limits, file restrictions and more. FileUpload does not require any kind of plugin like flash.

The component is using two Apache libraries : 

  • Commons IO
  • Commons File Upload

Requirements

NameValue
Primefaces  3.2 
Apache commons io  >=1.3.2
Apache Commons FileUpload

>=1.2.1

Dependencies configuration with Maven

Maven configuration

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>1.3.2</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.1</version>
        </dependency>

Webapp configuration

Your web.xml file should contains the following snippet to configure the Primefaces filter required to upload files.

Primefaces upload Fileupload Filter

     <!-- ############################################# -->
    <!-- # File upload                                      # -->
    <!-- ############################################# -->
    <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>
         <!-- Optional 
        <init-param>
            <param-name>uploadDirectory</param-name>
            <param-value>/var/bcom/temp</param-value>
        </init-param>
         -->
    </filter>
    
    <filter-mapping>
        <filter-name>PrimeFaces FileUpload Filter</filter-name>
        <servlet-name>Faces Servlet</servlet-name>
    </filter-mapping>

 Upload incompatible with Tomahawk fileupload

If you have already define a filter for another framework like Tomahawk you need to remove the previous filter

Apache Tomahawk is using the following extension filter : 

org.apache.myfaces.webapp.filter.ExtensionsFilter

If you keep the filter your file upload listener wiill never be invoked  

Your JavaServer Faces page

 JSF fileUpload Primefaces

    <h:form enctype="multipart/form-data">
        <p:fileUpload
            mode="advanced"
            fileUploadListener="#{uploaderBB.handleFileUpload}"
            allowTypes="/(\.|\/)(gif|jpg|jpeg|gif|png|PNG|GIF|JPG|JPEG)$/" 
            auto="true"/>
    </h:form>

Uploader Managed bean

In your uploader Managed Bean define a method handleFileUpload. This method will take care of the file uploaded located in the FileUploadEvent then using an outputStream you will write the file in your filesystem. 

Upload Managed Bean Session scoped

package com.ubiteck.samples.fileupload;

import java.io.File;
import java.io.IOException;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;


@ManagedBean
@SessionScoped
public class UploaderBB {

    public void handleFileUpload(FileUploadEvent event) {
        try {
            File targetFolder = new File("/var/uploaded/images");
            InputStream inputStream = event.getFile().getInputstream();
            OutputStream out = new FileOutputStream(new File(targetFolder,
                    event.getFile().getFileName()));
            int read = 0;
            byte[] bytes = new byte[1024];

            while ((read = inputStream.read(bytes)) != -1) {
                out.write(bytes, 0, read);
            }
            inputStream.close();
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
 

Uploading a file has never been so easy.

If you enjoyed this tutorial and want to promote it don't hesitate to click on 

Tags: version, /dependency, /version, apache, file, commons, primefaces, fileupload, upload, filter, commons-fileupload, filter-name, /filter-name, init-param

Comments  

 
+2 #3 kush 2012-11-26 06:03
Hi have problem with file limit attribute of fileUpload tag. In user guide primefaces guys has mentioned about this attribute. But when I tried this it is not limiting number of files to be uploaded. Plz help
Quote
 
 
+3 #2 Rafael 2012-10-04 13:16
I have a doubt: on multiple upload, all the files are sent at once, they are sent one by one (there should be some kind of line...). So, where the files that are not sent yet stay ?
Quote
 
 
+3 #1 gohohgle 2012-06-17 18:08
I applied most solution from internet, but only you mentioned about another filter. You solved my problem and save my time. Great thanks!
Quote
 

Add comment


Security code
Refresh

Java Tutorial on Facebook