GWT - FileUpload Widget



Introduction

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 com.google.gwt.user.client.ui.FileUpload 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

Sr.No. Constructor & Description
1

FileUpload()

Constructs a new file upload widget.

2

FileUpload(Element element)

This constructor may be used by subclasses to explicitly use an existing element.

Class Methods

Sr.No. Function name & Description
1

HandlerRegistration addChangeHandler(ChangeHandler handler)

Adds a ChangeEvent handler.

2

java.lang.String getFilename()

Gets the filename selected by the user.

3

java.lang.String getName()

Gets the widget's name.

4

boolean isEnabled()

Gets whether this widget is enabled.

5

void onBrowserEvent(Event event)

Fired whenever a browser event is received.

6

void setEnabled(boolean enabled)

Sets whether this widget is enabled.

7

void setName(java.lang.String name)

Sets the widget's name.

8

static 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 −

  • com.google.gwt.user.client.ui.UIObject

  • com.google.gwt.user.client.ui.Widget

  • 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 −

Step Description
1 Create a project with a name HelloWorld under a package com.tutorialspoint as explained in the GWT - Create Application chapter.
2 Modify HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Keep rest of the files unchanged.
3 Compile 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 = 'com.google.gwt.user.User'/>

   <!-- Inherit the default GWT style sheet.                       -->
   <inherits name = 'com.google.gwt.user.theme.clean.Clean'/>

   <!-- 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'/>

</module>

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

body {
   text-align: center;
   font-family: verdana, sans-serif;
}

h1 {
   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.

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

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

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

package com.tutorialspoint.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.FormPanel.SubmitCompleteEvent;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

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.
      form.setAction("http://www.tutorialspoint.com/gwt/myFormHandler");
      // set form to use the POST method, and multipart MIME encoding.
      form.setEncoding(FormPanel.ENCODING_MULTIPART);
      form.setMethod(FormPanel.METHOD_POST);
    
      //add a label
      panel.add(selectLabel);
      //add fileUpload widget
      panel.add(fileUpload);
      //add a button to upload the file
      panel.add(uploadButton);
      uploadButton.addClickHandler(new ClickHandler() {
         @Override
         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.submit();			          
            }				
         }
      });
   
      form.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {
         @Override
         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 
            Window.alert(event.getResults());				
         }
      });
      panel.setSpacing(10);
	  
      // Add form to the root panel.      
      form.add(panel);      

      RootPanel.get("gwtContainer").add(form);
   }	
}

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 = "org.apache.commons.io.FilenameUtils"%>
<%@page import = "java.util.List"%>
<%@page import = "java.util.Iterator"%>
<%@page import = "java.io.File"%>
<%@page import = "java.io.FileOutputStream"%>
<%@page import = "java.io.InputStream"%>

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

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

      while (iter.hasNext()) {
         FileItem item = (FileItem) iter.next();
      
         //handling a normal form-field
         if(item.isFormField()) {
            System.out.println("Got a form field");
            String name = item.getFieldName();
            String value = item.getString();
            System.out.print("Name:"+name+",Value:"+value);				
         
         } 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);
            fileOutSt.write(data);
            fileOutSt.close();
            out.print("File Uploaded Successfully!");
         }	
      }
   } catch(Exception e){
      out.print("File Uploading Failed!" + e.getMessage());
   }   
%>
gwt_form_widgets.htm
Advertisements