如何使用JSF / Primefaces上传文件? [英] How to Upload a file using JSF/Primefaces?

查看:159
本文介绍了如何使用JSF / Primefaces上传文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用< p:fileUpload> 来使用JSF2.0 / Primefaces上传文件。我还没有找到任何可以帮助我的文档。
$ b $ p我有两个表: Person(name,lastnam ....) code>和 file(id,path,name,size)
我想实现的场景是:


  • 用户订阅我的网站,我保存他的信息,包括上传的文件

  • 当文件上传时,我想保存它在我的磁盘上,并保存
    路径到我的数据库

    (保持用户和他的文件之间的关系)


    所以当用户按 Save 按钮时,我保存了所有这些信息。



    这是我的 index.xhtml

     < h:form> 
    < p:panel header =Add Userstyle =width:500px; font-size:14px>
    < h:panelGrid width =width:300px;列= 2 >


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

    < h:selectOneMenu id =statusvalue =#{AddPerson.status}>
    < f:selectItem itemValue =SingleitemLabel =Single/>
    < / h:selectOneMenu>

    < h:outputLabel value =Bith date/> < p:calendar value =#{AddPerson.birthdate}id =popupButtonCalshowOn =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}/>

    < p:growl id =messagesshowDetail =true/> // **例子:从primefaces展示** **


    < / h:panelGrid>
    < / p:面板>
    < / h:表格>

    这里是我的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);

    // **我也应该在这里添加文件的路径并保存在光盘上的文件!!!! **

    em.persist(用户);

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


    $ b


    解决方案

    在哪里执行fileUploadListener?我通常这样做:

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

    然后我的bean有一个处理文件上传事件的方法。这样的事情:

    pre $ public $ 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);
    字节buf [] =新字节[1024];
    int len; ((len = is.read(buf))> 0)
    out.write(buf,0,len);
    is.close();
    out.close();



    $ b

    保留对刚刚保存的文件路径的引用,并将其用于在你的addUserDB()方法中设置相应的用户属性。所以这真的是一个两步的过程。您首先将文件保存在服务器的某个位置,然后保存您的用户。


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

    解决方案

    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.

    这篇关于如何使用JSF / Primefaces上传文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆