Monday 6 May 2013

Upload File and send text field values using JSF and Primefaces


In my previous post, I showed how to upload a file using JSF and primefaces.
In this blog I will show how to upload a file along with text field value.
In this blog I will add a text field to the form and a field in the controller with setters and getters. So to transfer text field value to the controller, I will add an event to text field to update the managed bean on blur event.

 <h:form enctype="multipart/form-data">
<h:outputLabel value="Text Field here"/>
 <h:inputText value="#{fileUploadController.summary}">
<f:ajax event="blur"/>
</h:inputText>
<p:fileUpload fileUploadListener="#{fileUploadController.handleFileUpload}"
mode="advanced" update="messages, dt"  auto="true"/>
 <p:dataTable id="dt" var="filename" value="#{fileUploadController.filesList}">
<p:column>
 #{filename}
 </p:column>
 </p:dataTable>
<p:growl id="messages" showDetail="true"/>

 </h:form>



@ManagedBean
@SessionScoped
public class FileUploadController implements Serializable {

    private String summary;
    private List<String> filesList;

    public List<String> getFilesList() {
        return filesList;
    }

    public void setFilesList(List<String> filesList) {
        this.filesList = filesList;
    }

    public String getSummary() {
        return summary;
    }

    public void setSummary(String summary) {
        this.summary = summary;
    }

    public FileUploadController() {
        filesList = new ArrayList<String>();
    }

    public void handleFileUpload(FileUploadEvent event) {
        FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded. Textfield: "+summary);
        FacesContext.getCurrentInstance().addMessage(null, msg);
        UploadedFile file = event.getFile();
        System.out.println(file.getContents());
        filesList.add(file.getFileName());
        System.out.println("added to files list " + filesList + " with Summary field " + summary);
    }
}


And the result:


5 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. in case if you wanted to pass radio button value then use event="change" on behalf of event="blur".

    ReplyDelete
  3. Sometimes your blog is loading slowly, better find a better host.”,:-` transfer big files

    ReplyDelete