ravi
ravi

Reputation: 6336

Before Upload event in PrimeFaces 3.5

Is it possible to do some server side processing, before file upload in PrimeFaces 3.5? Let say the form contains some p:inputText elements, which needs to be filled before file upload, So how can I check that? Any event?

View looks like-

<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 is below-

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

Upvotes: 1

Views: 1884

Answers (2)

kolossus
kolossus

Reputation: 20691

<p:fileUpload/> has an onStart property which you can conveniently wire with a <p:remoteCommand/> component to fire a backing bean operation before the upload operation starts

      <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}"/>  

Upvotes: 3

KCP
KCP

Reputation: 312

I had a similar situation with a text field and file upload. I couldn't find any other way to do this except to check the name value in 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;
  }
}

Upvotes: 1

Related Questions