2013-05-03 140 views
0

我正在使用fileuplod primefaces。我有3个按钮。每个按钮都负责上传文件。我的第一个陡峭的是在我的bean上使用3种方法来上传每个文件。 有没有办法为所有类型制作相同的方法?每个文件都有他自己的目录。使用参数制作handleFileupload以共享方法

<h:form enctype="multipart/form-data" style="height:125px;width:75px;"> 

        <p:fileUpload auto="true" 
        fileUploadListener="#{composantbean.handleFileUpload(???,1)}" 
        sizeLimit="2097152" 
        label="Choose" 
        allowTypes="/(\.|\/)(pdf)$/" 
        description="Images"/> 
       </h:form> 

在我管理的bean,我想这个解决方案:

public void handleFileUpload(FileUploadEvent event,int i) { 
     String lienPDN =destination+"PDN\\"+FilenameUtils.getName(event.getFile().getFileName()); 
     File result = new File(lienPDN); 
     try { 
       FileOutputStream fileOutputStream = new FileOutputStream(result); 
       byte[] buffer = new byte[BUFFER_SIZE]; 
       int bulk; 
       InputStream inputStream = event.getFile().getInputstream(); 

       while (true) { 
        bulk = inputStream.read(buffer); 
        if (bulk < 0) { 
         break; 
         } 

      fileOutputStream.write(buffer, 0, bulk); 
      fileOutputStream.flush(); 
      } 

      fileOutputStream.close(); 
      inputStream.close(); 
      FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName()+ " is uploaded."); 
      FacesContext.getCurrentInstance().addMessage(null, msg); 
      selcetitem.setLienPdn(lienPDN); 
      } catch (IOException e) { 

         e.printStackTrace(); 
         FacesMessage error = new FacesMessage(FacesMessage.SEVERITY_ERROR,"The files were not uploaded!", ""); 
         FacesContext.getCurrentInstance().addMessage(null, error); 
         }  
     } 
+1

,问题是......? – Aquillo 2013-05-03 08:35:42

+0

hhhhh ..你是对的..我的问题是fileUploadListener =“#{composantbean.handleFileUpload(???,1)}”?????我在这里写的 – FERESSS 2013-05-03 08:45:13

回答

2

我想一个更好的办法可能是实现了三个handleFileUpload()方法。每个人都可以处理他们独特的代码(例如传递正确的文件路径)。从那里你可以拨打private void wrapUpUpload(String path, (...))

大部分这一切使您的代码可读。如果还阻止需要更改默认实现handleFileUpload()

例如为:请务必立即更换123与一些有意义

void handleFileUpload1(FileUploadEvent event) { 
    String path = "/uploads/1/"; 
    wrapUpUpload(path); 
} 

void handleFileUpload2(FileUploadEvent event) { 
    String path = "/uploads/2/"; 
    wrapUpUpload(path); 
} 

void handleFileUpload3(FileUploadEvent event) { 
    String path = "/uploads/3/"; 
    wrapUpUpload(path); 
} 

private void wrapUpUpload(String path, (...)) { 
    // Upload the file 
} 
+0

thx为您的合作:) – FERESSS 2013-05-03 09:06:30

+0

不客气! – Aquillo 2013-05-03 09:18:03