Upload File in Gwt to Client Side

GWT - FileUpload Widget



Introduction

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

Class Announcement

Following is the declaration for com.google.gwt.user.customer.ui.FileUpload form −

public course FileUpload     extends Widget       implements HasName, HasChangeHandlers        

CSS Style Rules

Following default CSS Style rules will be practical to all the TextBox widget. Y'all 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 exist used by subclasses to explicitly utilise 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 past the user.

3

java.lang.String getName()

Gets the widget'south name.

4

boolean isEnabled()

Gets whether this widget is enabled.

5

void onBrowserEvent(Outcome event)

Fired whenever a browser event is received.

6

void setEnabled(boolean enabled)

Sets whether this widget is enabled.

vii

void setName(java.lang.String proper noun)

Sets the widget's name.

eight

static FileUpload wrap(Element element)

Creates a FileUpload widget that wraps an existing <input type='file'> chemical element.

Methods Inherited

This form inherits methods from the following classes −

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

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

  • java.lang.Object

FileUpload Widget Instance

This example will take y'all through simple steps to show usage of a FileUpload Widget in GWT. Follow the following steps to update the GWT application nosotros created in GWT - Create Application affiliate −

Step Description
1 Create a projection with a name HelloWorld under a package com.tutorialspoint equally explained in the GWT - Create Awarding affiliate.
2 Alter HelloWorld.gwt.xml, HelloWorld.css, HelloWorld.html and HelloWorld.java as explained below. Proceed remainder of the files unchanged.
3 Compile and run the application to verify the result of the implemented logic.

Post-obit is the content of the modified module descriptor src/com.tutorialspoint/HelloWorld.gwt.xml.

<?xml version = "one.0" encoding = "UTF-viii"?> <module rename-to = 'helloworld'>    <!-- Inherit the cadre Web Toolkit stuff.                        -->    <inherits proper name = 'com.google.gwt.user.User'/>     <!-- Inherit the default GWT style canvas.                       -->    <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 = 'customer'/>    <source path = 'shared'/>  </module>        

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

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

Post-obit is the content of the modified HTML host file war/HelloWorld.html.

<html>    <head>       <championship>Hello World</title>       <link rel = "stylesheet" href = "HelloWorld.css"/>       <script language = "javascript" src = "helloworld/helloworld.nocache.js">       </script>    </caput>     <body>       <h1>FileUpload Widget Demonstration</h1>       <div id = "gwtContainer"></div>    </body> </html>        

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

package com.tutorialspoint.client;  import com.google.gwt.cadre.client.EntryPoint; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.event.dom.client.ClickHandler; import com.google.gwt.user.customer.Window; import com.google.gwt.user.client.ui.Push; 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       concluding FileUpload fileUpload = new FileUpload();       //create labels       Characterization selectLabel = new Label("Select a file:");       //create upload button       Push button uploadButton = new Push button("Upload File");       //pass activity to the grade to point to service treatment file        //receiving operation.       class.setAction("http://www.tutorialspoint.com/gwt/myFormHandler");       // set form to utilize the Mail 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 push to upload the file       console.add(uploadButton);       uploadButton.addClickHandler(new ClickHandler() {          @Override          public void onClick(ClickEvent result) {             //go the filename to be uploaded             String filename = fileUpload.getFilename();             if (filename.length() == 0) {                Window.alert("No File Specified!");             } else {                //submit the class                form.submit();			                       }				          }       });           course.addSubmitCompleteHandler(new FormPanel.SubmitCompleteHandler() {          @Override          public void onSubmitComplete(SubmitCompleteEvent event) {             // When the form submission is successfully completed, this              //outcome is fired. Assuming the service returned a response              //of type text/html, we tin get the result text hither              Window.alert(event.getResults());				          }       });       panel.setSpacing(10); 	         // Add class to the root panel.             form.add(panel);              RootPanel.get("gwtContainer").add(grade);    }	 }        

One time yous are ready with all the changes washed, permit united states compile and run the application in development style as we did in GWT - Create Application chapter. If everything is fine with your application, this volition produce following result −

GWT FileUpload Widget

Following is the java server page lawmaking snippet demonstrating server side adequacy for file upload. We're using Common IO and Eatables FileUpload libraries to add file-upload adequacy to server side folio. File volition 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.eatables.fileupload.deejay.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 = "coffee.util.Iterator"%> <%@page import = "java.io.File"%> <%@page import = "java.io.FileOutputStream"%> <%@page import = "coffee.io.InputStream"%>  <%    // Create a manufacturing plant for deejay-based file items    FileItemFactory mill = new DiskFileItemFactory();    // Create a new file upload handler    ServletFileUpload upload = new ServletFileUpload(manufactory);    try {       // Parse the request          List items = upload.parseRequest(request);         // Process the uploaded items          Iterator iter = items.iterator();        while (iter.hasNext()) {          FileItem particular = (FileItem) iter.side by side();                 //handling a normal form-field          if(item.isFormField()) {             System.out.println("Got a form field");             String name = detail.getFieldName();             Cord value = item.getString();             Organization.out.print("Name:"+name+",Value:"+value);				                    } else {                           //treatment file loads             System.out.println("Not course field");             Cord 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.impress("Field Proper name:"+fieldName +",File Proper name:"+fileName);             System.out.print("Content Type:"+contentType                +",Is In Retention:"+isInMemory+",Size:"+sizeInBytes);			                           byte[] data = detail.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!");          }	       }    } take hold of(Exception due east){       out.print("File Uploading Failed!" + east.getMessage());    }    %>        

gwt_form_widgets.htm

rileyefrely1972.blogspot.com

Source: https://www.tutorialspoint.com/gwt/gwt_fileupload_widget.htm

0 Response to "Upload File in Gwt to Client Side"

Enregistrer un commentaire

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel