Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Upload a file using JSF/Primefaces?

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();
    }

}
like image 347
Julie Avatar asked Dec 06 '22 16:12

Julie


2 Answers

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.

like image 77
Andre Avatar answered Feb 21 '23 04:02

Andre


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
    }
}
like image 30
rags Avatar answered Feb 21 '23 04:02

rags