Forms with FileUpload in GWT

In this tutorial we are going to work on creating a form in GWT, and then we are going to work through processing the form from a Java servlet. File uploads with AJAX is certainly one of the more difficult aspects of programming on the client side, but with GWT you can easily implement an AJAX file upload. On the server side we are going to work with Apache Commons to process the content of the GWT form.

To complete this tutorial you will need to download the following items.

  1. Apache Commons File Upload
  2. Apache Commons IO – Required dependency for Apache Commons File Upload

Let’s start by creating a new GWT web application in Netbeans, and we’ll call it FileUpload. Once we have created the new project, we need to add the following code to the onModuleLoad method of the MainEntryPoint file.

// Create a FormPanel and point it at a service.
final FormPanel form = new FormPanel();
 //The /myFormHandler is a servlet
form.setAction("/myFormHandler");
 
 // Because we're going to add a FileUpload widget, we'll need to set the
// form to use the POST method, and multipart MIME encoding.
//VERY IMPORTANT when using FileUpload
form.setEncoding(FormPanel.ENCODING_MULTIPART);
form.setMethod(FormPanel.METHOD_POST);
 
// Create a panel to hold all of the form widgets.
VerticalPanel panel = new VerticalPanel();
form.setWidget(panel);
 
// Create a TextBox, giving it a name so that it will be submitted.
final TextBox tb = new TextBox();
tb.setName("textBoxFormElement");
panel.add(tb);
 
// Create a ListBox, giving it a name and some values to be associated with
 // its options.
ListBox lb = new ListBox();
lb.setName("listBoxFormElement");
lb.addItem("foo", "fooValue");
lb.addItem("bar", "barValue");
lb.addItem("baz", "bazValue");
panel.add(lb);
 
// Create a FileUpload widget.
FileUpload upload = new FileUpload();
upload.setName("uploadFormElement");
panel.add(upload);
 
// Add a 'submit' button.
panel.add(new Button("Submit", new ClickHandler() {
 
      public void onClick(ClickEvent event) {
           form.submit();
      }
}));

The above code creates a new FormPanel and adds some widgets to it. Note: Only widgets that implement the HasName interface can be added to a form panel. Here is a list of the GWT widgets that implement HasName.

  • TextBox
  • PasswordTextBox
  • RadioButton
  • SimpleRadioButton
  • CheckBox
  • SimpleCheckBox
  • TextArea
  • ListBox
  • FileUpload
  • Hidden

Before we process the form on the server side, we need to add an event handler for just before submission of the form and when the submission of the form is complete. The addSubmitHandler provides us a way to verify the form prior to submission, and if the form verification fails you can call event.cancel() to cancel the submission. The addSubmitCompleteHandler allows you to perform any necessary operations after a successful submission of the form has completed. So now let’s add these two event handlers to our form.

// Add an event handler to the form.
form.addSubmitHandler(new FormPanel.SubmitHandler() {
 
      public void onSubmit(SubmitEvent event) {
           // This event is fired just before the form is submitted. We can take
           // this opportunity to perform validation.
           if (tb.getText().length() == 0) {
               Window.alert("The text box must not be empty");
               event.cancel();
           }
      }
});
form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
 
   public void onSubmitComplete(SubmitCompleteEvent event) {
         // When the form submission is successfully completed, this event is
         // fired. Assuming the service returned a response of type text/html,
        // we can get the result text here (see the FormPanel documentation for
        // further explanation).
        Window.alert(event.getResults());
    }
});

Finally we just need to add the form to our RootPanel.

At this point the client side coding is done, but we still need to add our servlet to process the form on the server. In the server package create a servlet called myFormHandler, and in Netbeans you can just keep all of the default settings in the New File wizard. Next you can just delete out the contents of the processRequest method.

If you haven’t already done so, you need to download Apache Commons IO and Apache Commons File Upload. Once you have downloaded both libraries, you need to unzip them and add them to your web application. You are now able to process multipart MIME encoded forms. Just add the following code to your processRequest method.

response.setContentType("text/html;charset=UTF-8");
 
//verify that the request is multipart
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
 
FileItemFactory factory = new DiskFileItemFactory();
 
ServletFileUpload upload = new ServletFileUpload(factory);
try {
     //get the items from the request object
     List items = upload.parseRequest(request);
 
     Iterator iter = items.iterator();
     while(iter.hasNext()){
           Object obj = iter.next();
           //make sure the object is not null
           if(obj == null){
                continue;
           }
 
            FileItem item = (FileItem)obj;
 
           //if item is a form field then get the value from the item
          if(item.isFormField()){
              String name = item.getName();
              if(name.compareTo("textBoxFormElement")==0){
                   //do something with the text box value
                   String value = item.getString();
              }else{
                   //do something with the list box value
                   String value = item.getString();
              }
          //if the item is not a form field, you know you have
         //an uploaded file, and therefore you need to process
         //it as such.
        }else if(!item.isFormField()){
 
                //Here we can do whatever we want with the uploaded file.
               String name = item.getName();
        }
  }
 
     response.getWriter().write("Success in processing multipart MIME form");
} catch (Exception ex) {
}

For more information on Apache Commons File Upload you can click here.

As always if you have any questions, please leave a comment.

Rating 3.33 out of 5
  1. Looking at the Server side … Just wondering – shouldn’t the line “String name = item.getName()”:

    //if item is a form field then get the value from the item
    if(item.isFormField()){
    THIS LINE ***** >> String name = item.getName();

    be replaced with:
    //if item is a form field then get the value from the item
    if(item.isFormField()){
    THIS LINE ***** >> String name = item.getFieldName();

    Since it is a form field??

    Jesper

    • DHorst
    • August 13th, 2009

    Thanks for this fine tutorial. Can you provide the NetBeans-Project (or Eclipse) download?

    • Stephan
    • August 13th, 2009

    At what point can you pass this file to some server side code for processing.

    I am using ecllipse and want to pass a text file so I can read each line. How would you suggest I do this?

    Thanks for any time you do give to this question.

    Stephan

    • KK
    • August 13th, 2009

    hi,

    do I need make any changes in web.xml or gwt.xml file to make this servlet work?

    • born2bwild
    • August 13th, 2009

    Hi, this makes perfect sense… I have implemented my app quite similar to this.

    However, do you have any idea how to preview an image on the client side, before we send to our servlet and do further processing!?!

  1. August 13th, 2009
  2. August 13th, 2009

Spam Protection by WP-SpamFree