GWT - FileUpload Widget



The FileUpload widget wraps the HTML <input type='file'> element. This widget must be used with FormPanel if it is to be submitted to a server.

Class declaration

Following is the declaration for class:

public class FileUpload 
   extends Widget
      implements HasName, HasChangeHandlers

CSS style rules

Following default CSS Style rules will be applied to all the TextBox widget. You can override it as per your requirements.

.gwt-FileUpload {}

Class constructors

S.N.Constructor & Description
Constructs a new file upload widget.
2FileUpload(Element element)
This constructor may be used by subclasses to explicitly use an existing element.

Class methods

S.N.Function name & Description
1HandlerRegistration addChangeHandler(ChangeHandler handler)
Adds a ChangeEvent handler.
2java.lang.String getFilename()
Gets the filename selected by the user.
3java.lang.String getName()
Gets the widget's name.
4boolean isEnabled()
Gets whether this widget is enabled.
5void onBrowserEvent(Event event)
Fired whenever a browser event is received.
6void setEnabled(boolean enabled)
Sets whether this widget is enabled.
7void setName(java.lang.String name)
Sets the widget's name.
8static FileUpload wrap(Element element)
Creates a FileUpload widget that wraps an existing <input type='file'> element.

Methods inherited

This class inherits methods from the following classes:



  • java.lang.Object

FileUpload Widget Example

This example will take you through simple steps to show usage of a FileUpload Widget in GWT. Follow the following steps to update the GWT application we created in GWT - Create Application chapter:

1Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Application chapter.
2Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and as explained below. Keep rest of the files unchanged.
3Compile and run the application to verify the result of the implemented logic.

Following is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version="1.0" encoding="UTF-8"?>
<module rename-to='helloworld'>
  <!-- Inherit the core Web Toolkit stuff.                        -->
  <inherits name=''/>

  <!-- Inherit the default GWT style sheet.                       -->
  <inherits name=''/>

  <!-- Specify the app entry point class.                         -->
  <entry-point class='com.tutorialspoint.client.HelloWorld'/>

  <!-- Specify the paths for translatable code                    -->
  <source path='client'/>
  <source path='shared'/>


Following is the content of the modified Style Sheet file war/HelloWorld.css.

   text-align: center;
   font-family: verdana, sans-serif;
   font-size: 2em;
   font-weight: bold;
   color: #777777;
   margin: 40px 0px 70px;
   text-align: center;
.gwt-FileUpload {
   color: green; 

Following is the content of the modified HTML host file war/HelloWorld.html.

<title>Hello World</title>
   <link rel="stylesheet" href="HelloWorld.css"/>
   <script language="javascript" src="helloworld/helloworld.nocache.js">

<h1>FileUpload Widget Demonstration</h1>
<div id="gwtContainer"></div>


Let us have following content of Java file src/com.tutorialspoint/ which will demonstrate use of FileUpload widget.

package com.tutorialspoint.client;


public class HelloWorld implements EntryPoint {
   public void onModuleLoad() {
      VerticalPanel panel = new VerticalPanel();
      //create a FormPanel 
      final FormPanel form = new FormPanel();
      //create a file upload widget
      final FileUpload fileUpload = new FileUpload();
      //create labels
      Label selectLabel = new Label("Select a file:");
      //create upload button
      Button uploadButton = new Button("Upload File");
      //pass action to the form to point to service handling file 
      //receiving operation.
      // set form to use the POST method, and multipart MIME encoding.
      //add a label
      //add fileUpload widget
      //add a button to upload the file
      uploadButton.addClickHandler(new ClickHandler() {
         public void onClick(ClickEvent event) {
            //get the filename to be uploaded
            String filename = fileUpload.getFilename();
            if (filename.length() == 0) {
               Window.alert("No File Specified!");
            } else {
               //submit the form
      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 
      // Add form to the root panel.      


Once you are ready with all the changes done, let us compile and run the application in development mode as we did in GWT - Create Application chapter. If everything is fine with your application, this will produce following result:

GWT FileUpload Widget
  • Following is the java server page code snippet demonstrating server side capability for file upload

  • We're using Common IO and Commons FileUpload libraries to add file-upload capability to server side page.

  • File will be uploaded to uploadFiles folder relative to location where upload.jsp is located on server side.

<%@page import="org.apache.commons.fileupload.FileItemFactory"%>
<%@page import="org.apache.commons.fileupload.disk.DiskFileItemFactory"%>
<%@page import="org.apache.commons.fileupload.servlet.ServletFileUpload"%>
<%@page import="org.apache.commons.fileupload.FileItem"%>
<%@page import=""%>
<%@page import="java.util.List"%>
<%@page import="java.util.Iterator"%>
<%@page import=""%>
<%@page import=""%>
<%@page import=""%>

   // Create a factory for disk-based file items
   FileItemFactory factory = new DiskFileItemFactory();
   // Create a new file upload handler
   ServletFileUpload upload = new ServletFileUpload(factory);
      // Parse the request
         List items = upload.parseRequest(request); 

         // Process the uploaded items
         Iterator iter = items.iterator();

         while (iter.hasNext()) {
            FileItem item = (FileItem);
            //handling a normal form-field
            if(item.isFormField()) {
               System.out.println("Got a form field");
               String name = item.getFieldName();
               String value = item.getString();
            } else {//handling file loads
               System.out.println("Not form field");
               String fieldName = item.getFieldName();
               String fileName = item.getName();
               if (fileName != null) {
                  fileName = FilenameUtils.getName(fileName);
               String contentType = item.getContentType();
               boolean isInMemory = item.isInMemory();
               long sizeInBytes = item.getSize();
               System.out.print("Field Name:"+fieldName
               +",File Name:"+fileName);
               System.out.print("Content Type:"+contentType
               +",Is In Memory:"+isInMemory+",Size:"+sizeInBytes);			 
               byte[] data = item.get();
               fileName = getServletContext()
                         .getRealPath( "/uploadedFiles/" + fileName);
               System.out.print("File name:" +fileName);			
               FileOutputStream fileOutSt = new FileOutputStream(fileName);
               out.print("File Uploaded Successfully!");
    } catch(Exception e){
	out.print("File Uploading Failed!" + e.getMessage());