lundi 21 février 2011

Upload files / image with JSF and primfaces

the current versions of the Java web standards (servlets, JSP, and JSF) do not offer any help for upload files or pictures. Fortunately, there are third-party frameworks, such as  Apache Commons File UploadApache Tomahowk Richfaces, and primfaces

Primfaces provide JSF components that go beyond the JSF specification. These components are compatible with the JSF 2 with a little of bug

This article aims to provide detailed steps to develop an exemple of how to upload file using jsf 2 and primfaces and how to show it again into xhtml file.

The example in this tutorial creates a web page named :

  • upload_file.xhtml : contains a form for upload picture
  • show_image.xhtml to show picture

Preaparing the exemple

We need those librairies into project class path:

After adding the JAR's to class path we need to make changes into web.xml :

              PrimeFaces FileUpload Filter        org.primefaces.webapp.filter.FileUploadFilter                                    thresholdSize            51200                               uploadDirectory            /tmpDir/                        PrimeFaces FileUpload Filter        Faces Servlet    

Before creating the JSF pages and managed bean , we need first to add ower class Utils in my last post Image to byte array and byte array to image
this methode will be used :

public static byte[] InputStreamToByte(InputStream fis) throws FileNotFoundException {        ByteArrayOutputStream bos = new ByteArrayOutputStream();        byte[] buf = new byte[1024];        try {            for (int readNum; (readNum = != -1;) {                bos.write(buf, 0, readNum);                System.out.println("read " + readNum + " bytes,");            }            byte[] bytes = bos.toByteArray();            return bytes;        } catch (IOException ex) {            ex.printStackTrace();            return null;        }    }
and to create the jsf 2 managed bean which will be providing the required services for the JSF pages that will be created later dont forget getters and setters methode :
@ManagedBean@SessionScopedpublic class UploadImage { private StreamedContent image;    /**     * Used to upload image from jsf pages     * @param event     */    public String imageUpload(FileUploadEvent event) {        try {            /** Convert file from input stream to bytes */            byte[] bytearray = Utils.InputStreamToByte(event.getFile().getInputstream())             /*             * bytearray used to store picture into database              */              InputStream ist = new ByteArrayInputStream(bytearray);            /*             * StreamedContent Object used to show the picture in jsf pages             * we need to convert again bytearray to InputStream             */            image = new DefaultStreamedContent(ist, "image/jpg");            FacesMessage msg = new FacesMessage("Succesful picture is uploaded.");            FacesContext.getCurrentInstance().addMessage(null, msg);            /** we dont need to use faces-config to navigate in jsf 2 */            return "/show_image.xhtml"        } catch (Exception e) {            FacesMessage msg = new FacesMessage("Exception happen");            FacesContext.getCurrentInstance().addMessage(null, msg);            e.printStackTrace();            return null;        }    }}
Now, we are ready to create the first web page named upload_file.xhtml that contains a form to upload file
Create the next web page named show_file.xhtml that contains a tag to show image
Note - you can add ajax fonction to show picture when upload just in your managed bean change imageUpload methode to retur void and copy p:graphicImage into upload_image.picture and add update="image" to p:fileUpload tag

Aucun commentaire:

Enregistrer un commentaire