gwt
File Upload Example
With this example we are going to demonstrate how to make a File Upload using the Google Web Toolkit, that is an open source set of tools that allows web developers to create and maintain complex JavaScript front-end applications in Java. In short, to make a File Upload we have performed the steps below:
- The
FileUploadExample
class implements thecom.google.gwt.core.client.EntryPoint
interface to allow the class to act as a module entry point. It overrides itsonModuleLoad()
method. - Create a new VerticalPanel.
- Add a Label to the VerticalPanel.
- Create a new Instance of FileUpload
- Create a Button for submit. Add a ClickHandler to the button and override its
onClick(ClickEvent event)
method to handle click events. For example you can check the extension of a file before uploading it. - Add the widgets to the VerticalPanel.
- Add the VerticalPanel to the
RootPanel
, that is the panel to which all other widgets must ultimately be added.
Let’s take a look at the code snippet that follows:
package com.javacodegeeks.snippets.enterprise; 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.HTML; import com.google.gwt.user.client.ui.RootPanel; import com.google.gwt.user.client.ui.VerticalPanel; public class FileUploadExample implements EntryPoint { //Allowed files (.pdf for this example) private final String extention = ".pdf"; @Override public void onModuleLoad() { // Create new Instance of vertical panel to align the widgets VerticalPanel vp = new VerticalPanel(); // Add label vp.add(new HTML("")); // Create new Instance of FileUpload final FileUpload fileUpload = new FileUpload(); // Create button for submit Button uploadButton = new Button("Upload"); // Add ClickHandler to the button uploadButton.addClickHandler(new ClickHandler() { @Override public void onClick(ClickEvent event) { //Get file name String filename = fileUpload.getFilename(); // Check the length of the filename if (filename.length() != 0) { // Get the extention String fileExtention = filename.substring(filename.length() - extention.length(), filename.length()); // Check if the extention is '.pdf' if (!fileExtention.equals(extention)) { Window.alert("Only .pdf files are allowed"); } Window.alert("File was successfully uploaded"); } else Window.alert("No file choosen"); } }); // Add widgets to Vertical Panel vp.add(fileUpload); vp.add(uploadButton); //Add Vertical Panel to Root Panel RootPanel.get().add(vp); } }
This was an example of how to make a File Upload using the Google Web Toolkit.
OK, but how could one get the text inside the file in order to store that?
I have checked the above code it will work for single file,how can we upload multiple files and how can we get names