簡體   English   中英

如何使用JSF / Primefaces上傳文件?

[英]How to Upload a file using JSF/Primefaces?

我想使用<p:fileUpload>使用JSF2.0 / Primefaces上傳文件。 我還沒有找到任何可以幫助我的文檔。

我有兩個表: Person(name,lastnam....)file(id,path,name,size)我想要實現的場景是:

  • 用戶訂閱我的網站,我保存他的信息,包括上傳的文件
  • 上傳文件時,我想將其保存在我的磁盤上並將路徑保存到我的數據庫中
    (保持用戶和他的文件之間的關系)

因此,當用戶按下保存按鈕按鈕時,我保存所有這些信息。

這是我的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>

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

}

fileUploadListener的實現在哪里? 我通常只是這樣做:

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

然后我的bean有一個處理文件上傳事件的方法。 像這樣的東西:

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

保留對剛剛保存的文件路徑的引用,並將其用於在addUserDB()方法中設置相應的用戶屬性。 所以這真的是一個兩步過程。 首先將文件保存在服務器中的某個位置,然后保存用戶。

fileUpload有fileUploadListener。 請注意,您應該實現邏輯以在托盤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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM