4

I want to upload a file using JSF2.0/Primefaces using <p:fileUpload>. I haven't found any documentation that can help me.

I have two tables: Person(name,lastnam....) and file(id,path,name,size) The scenario that I want to achieve is:

  • A user subscribe into my website, I save his information including the files uploaded
  • When the file is uploaded, I want to save it on my disk and save the path into my database
    (to keep the relation between a user and his files)

So when the user press the button Save button, I save all this information.

Here is my index.xhtml

<h:form >
     <p:panel header="Add User"    style="width: 500px; font-size: 14px">
        <h:panelGrid width="width: 300px;"    columns="2">


         <h:outputLabel style="font-size: 13px" value="Name" /> <h:inputText value="#{AddPerson.lastname}" />
         <h:outputLabel value="LastName"/> <h:inputText value="#{AddPerson.name}" />

          <h:outputLabel value="Marital Status"/>
          <h:selectOneMenu id="status" value="#{AddPerson.status}">
             <f:selectItem itemValue="Single" itemLabel="Single"/>
             <f:selectItem itemValue="Married" itemLabel="Married"/>
          </h:selectOneMenu>

          <h:outputLabel value="Bith date "/> <p:calendar value="#{AddPerson.birthdate}" id="popupButtonCal" showOn="button" />
          <h:outputLabel value="email"/><h:inputText value="#{AddPerson.email}" />
           <h:outputLabel value="mobile"/><h:inputText value="#{AddPerson.mobile}" />
           <h:outputLabel value="fax"/><h:inputText value="#{AddPerson.fax}" />
           <h:outputLabel value="Job"/><h:inputText value="#{AddPerson.Job}" />
           <h:outputLabel value="addresse"/><h:inputText value="#{AddPerson.addresse}" />
           <h:outputLabel value="code"/><h:inputText value="#{AddPerson.code}" />
           <h:outputLabel value="Country"/><h:inputText value="#{AddPerson.country}" />
           <h:outputLabel value="login"/><h:inputText value="#{AddPerson.login}" />
           <h:outputLabel value="password"/><h:inputText value="#{AddPerson.password}" />

           <h:outputLabel value="CV"/>  <input type="file" name="uploaded_file"/>
           <p:fileUpload fileUploadListener="#{AddPerson...."   update="messages"   sizeLimit="500000"    allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>  
            <p:growl id="messages" showDetail="true"/>     // **example :taken from primefaces showcases**

            <h:commandButton action="#{AddPerson.addUserDB}"  value="Add User" />

       </h:panelGrid>
       </p:panel>
</h:form>

and here is My bean

public void addUserDB() {
    try {

        EntityTransaction entr = em.getTransaction();
        entr.begin();

        Person user = new Person();

        user.setNom(lastname);
        user.setPrenom(name);
        user.setCodepostal(code);
        user.setEmail(email);
        user.setEtatCivil(status);
        user.setFax(fax);
        user.setDateNaissance(birthdate);
        user.setMobile(mobile);
        user.setAdresse(addresse);
        user.setPays(country);
        user.setLogin(login);
        user.setPassword(password);

        //**I should also add here the path of the file to the table and save the file on the disc  !!!!**         

        em.persist(user);

        entr.commit();
    } catch (Exception e) {
        System.out.println(e.getMessage());
        System.out.println("Failed");
    } finally {
        em.close();
    }

}
S1LENT WARRIOR
  • 11,704
  • 4
  • 46
  • 60
Julie
  • 563
  • 6
  • 10
  • 23
  • 2
    PrimeFaces has a showcase with concrete examples: http://www.primefaces.org/showcase/ui/fileUploadHome.jsf PrimeFaces also has an Users Guide: http://www.primefaces.org/documentation.html – BalusC Mar 01 '12 at 19:41
  • Did you add two jar files under WEB-INF/lib; common-fileupload.jar and common.io.jar – Günay Gültekin Oct 25 '13 at 06:12

2 Answers2

11

where's the implementation of the fileUploadListener? I normally just do this:

<p:fileUpload cancelLabel="#{msg['cancel']}" update="someComponent" 
fileUploadListener="#{someBean.uploadListener}"
multiple="false" sizeLimit="1000000" allowTypes="/(\.|\/)(gif|jpe?g|png)$/" />

Then my bean has a method that handles the file upload event. Something like this:

public void fileUpload(FileUploadEvent event) throws IOException {
    String path = FacesContext.getCurrentInstance().getExternalContext()
            .getRealPath("/");
    SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmss");
    String name = fmt.format(new Date())
            + event.getFile().getFileName().substring(
                  event.getFile().getFileName().lastIndexOf('.'));
    File file = new File(path + "catalogo_imagens/temporario/" + nome);

    InputStream is = event.getFile().getInputstream();
    OutputStream out = new FileOutputStream(file);
    byte buf[] = new byte[1024];
    int len;
    while ((len = is.read(buf)) > 0)
        out.write(buf, 0, len);
    is.close();
    out.close();
}

Keep a reference to the file path that has just been saved and use that for setting the corresponding user property in your addUserDB() method. So it's really a two step process. You first save the file somewhere in the server, then you save your user.

Andre
  • 3,874
  • 3
  • 35
  • 50
  • I have tried this, but the file was saved under D:\MyDocuments\MySites\MySiteExample\build\web\eventImage137.jpg Is there any way not to save it in the BUILD folder, but in the "real" web folder? – vtomic85 Jun 12 '14 at 19:43
  • 2
    You can save wherever you want, really. Just set the path variable accordingly. Try not to hardcode it though, as you might have trouble if you end up running this in a different server with a different OS. Maybe use an environment variable or a java parameter for setting up the location where the file will be saved. – Andre Jun 13 '14 at 12:56
  • Hi @Andre could you clarify who to "use an environment variable or a java parameter for setting up the location where the file will be saved",please – K.Ariche Nov 24 '14 at 23:36
4

fileUpload has fileUploadListener. Note that, you should implement the logic to save the file contents yourself in your backing bean.

<p:fileUpload fileUploadListener="#{fileBean.handleFileUpload}">

public class FileBean {
    public void handleFileUpload(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        String fileName = file.getFileName();
        long fileSize = file.getSize();
        InputStream myInputStream = file.getInputstream();
        //Save myInputStream in a directory of your choice and store that path in DB
    }
}
rags
  • 2,580
  • 19
  • 37