2012-03-01 3 views
3

<p:fileUpload>을 사용하여 JSF2.0/Primefaces를 사용하여 파일을 업로드하고 싶습니다. 나를 도울 수있는 문서를 찾지 못했습니다. Person(name,lastnam....)file(id,path,name,size) 내가 달성하고자하는 시나리오는 다음과 같습니다 : I 파일 인 경우 파일을 포함하여 자신의 정보가 JSF/Primefaces를 사용하여 파일을 업로드하는 방법은 무엇입니까?

  • 을 업로드 저장

    • 사용자는 내 웹 사이트에 가입

      나는 두 개의 테이블이 업로드, 나는

    (사용자 자신의 파일 사이의 관계를 유지하기 위해) 내 디스크에 저장하고 내 데이터베이스에 경로를 저장하려면

    버튼 버튼을 누르면이 모든 정보가 저장됩니다. 여기

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

    PrimeFaces 구체적인 예제와 함께 쇼케이스를 갖는다. html – BalusC

    +0

    WEB-INF/lib 아래에 두 개의 jar 파일을 추가 했습니까? common-fileupload.jar 및 common.io.jar –

    답변

    10

    곳 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() 메소드에 해당 사용자의 속성을 설정하는 것을 사용 된 파일 경로에 대한 참조를 유지합니다. 그래서 그것은 실제로 두 단계 과정입니다. 먼저 파일을 서버의 어딘가에 저장 한 다음 사용자를 저장합니다.

    +0

    시도했지만이 파일은 D : \ MyDocuments \ MySites \ MySiteExample \ build \ web \ eventImage137.jpg 아래에 저장되었습니다. BUILD 폴더에 있지만 "실제"웹 폴더에 있습니까? – vtomic85

    +2

    정말로 원하는 곳에 저장할 수 있습니다. 그에 따라 경로 변수를 설정하면됩니다. 다른 OS가있는 다른 서버에서이 작업을 끝내면 문제가 발생할 수 있으므로 하드 코드하지 마십시오. 파일을 저장할 위치를 설정하기 위해 환경 변수 또는 java 매개 변수를 사용할 수 있습니다. – Andre

    +0

    안녕하세요 @Andre는 "파일을 저장할 위치를 설정하기 위해 환경 변수 또는 자바 매개 변수를 사용할 사용자"를 명확히 할 수 있습니까? –

    3

    fileUpload에는 fileUploadListener가 있습니다. 파일 내용을 백업 빈에 직접 저장하는 로직을 구현해야합니다. http://www.primefaces.org/showcase/ui/fileUploadHome.jsf PrimeFaces 또한 사용자 설명서가 있습니다 : http://www.primefaces.org/documentation

    <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 
        } 
    } 
    
    관련 문제