在PrimeFaces 3.5中的上传事件之前

时间:2013-04-18 11:13:08

标签: jsf-2 primefaces

在PrimeFaces 3.5中上传文件之前,是否可以进行一些服务器端处理?假设表单包含一些p:inputText元素,需要在文件上传之前填充,那么我该如何检查呢?有什么事吗?

视图看起来像 -

<h:form enctype="multipart/form-data">
    <p:inputText value="#{fileUploadController.name}" id="name" label="Name" />
    <p:inputText value="#{fileUploadController.about}" id="about" label="About" />
    <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
            mode="advanced" 
            update="messages"
            sizeLimit="100000" 
            allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>

    <p:growl id="messages" showDetail="true"/>

</h:form>

ManagedBean位于 -

之下
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

public class FileUploadController {

    private String name;
    private String about;
    //Getters & Setters

    public void beforeUpload(){
    if(getName().isEmpty()||getAbout().isEmpty())
        FacesMessage msg = new FacesMessage("Error", "Name or About cannot be empty");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
        FacesContext.getCurrentInstance().addMessage(null, msg);
    }
}

2 个答案:

答案 0 :(得分:3)

<p:fileUpload/>具有onStart属性,您可以方便地与<p:remoteCommand/>组件连接以在上传操作开始之前触发支持bean操作

      <p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
        mode="advanced" 
        onstart="startSomething();"
        update="messages"
        sizeLimit="100000" 
        allowTypes="/(\.|\/)(gif|jpe?g|png)$/"/>

      <p:remoteCommand name="startSomething" action="#{bean.startSomething}"/>  

答案 1 :(得分:1)

我的文字字段和文件上传情况类似。除了检查handleFileUpload中的名称值之外,我找不到任何其他方法。

public void handleFileUpload(FileUploadEvent event){
  HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();`
  name =req .getRequestParams("formId:name")
  if(name==null){
   FacesMessage msg = new FacesMessage("Error", "Name or About cannot be empty")
   return;
  }
}