Wednesday, December 2, 2009

FileUpload with GWT-Ext and java EE servlet

This simple web application will demonstrate how to upload an image file by using GWT-Ext (on client side) and java EE servlet instead of GWT remote service (on server side). This web application allows user to browse for an image file and submit it to the apache tomcat web server, the request will be processed by a servlet deployed on the web server, it will extract the request for binary data and save it into the specified directory on the deployment location of web application. Once the image file is registered successfully it will be shown up on the current page.

To get start, we need to create a web application project, you can follow my previous post
Using WindowBuilder for Google Web Toolkit & GWT-EXT, Once project is setup, we need a window to interact with the user, which looks like:

You can create a window by using the following code:

package com.mycompany.project.client;

import com.google.gwt.core.client.GWT;
import com.gwtext.client.core.Connection;
import com.gwtext.client.core.EventObject;
import com.gwtext.client.data.FieldDef;
import com.gwtext.client.data.RecordDef;
import com.gwtext.client.data.StringFieldDef;
import com.gwtext.client.data.XmlReader;
import com.gwtext.client.widgets.Button;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.Window;
import com.gwtext.client.widgets.event.ButtonListenerAdapter;
import com.gwtext.client.widgets.form.Form;
import com.gwtext.client.widgets.form.FormPanel;
import com.gwtext.client.widgets.form.TextField;
import com.gwtext.client.widgets.form.event.FormListenerAdapter;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.Image;

public class FileUploadWindow extends Window {
FormPanel formPanel = new FormPanel();
Grid grid = new Grid(1,1);
public FileUploadWindow() {
super("Photo Upload");
setSize("500px", "400px");
formPanel.setFileUpload(true);
//setup error reader to process from submit response from server
RecordDef errorRecordDef = new RecordDef(new FieldDef[]{
new StringFieldDef("id"),
new StringFieldDef("msg")
});
XmlReader errorReader = new XmlReader("field", errorRecordDef);
errorReader.setSuccess("@success");
formPanel.setErrorReader(errorReader);

final TextField textField = new TextField("Photo", "file");
textField.setInputType("file");
textField.setSize("334px", "28px");
formPanel.add(textField);
this.add(formPanel);
this.addButton(new Button("Submit",new ButtonListenerAdapter() {
public void onClick(Button button, EventObject e) {
MessageBox.confirm("Confirm", "Do you want to submit?",
new MessageBox.ConfirmCallback() {
public void execute(String btnID) {
if (btnID.equals("yes")) {
formPanel.getForm().submit(GWT.getModuleBaseURL()+"upload", null, Connection.POST, "Saving Data...", false);
}
}
});
}
}));
formPanel.addFormListener(new FormListenerAdapter(){
public boolean doBeforeAction(Form form) {return true;}
public void onActionComplete(Form form, int httpStatus, java.lang.String responseText){
Image image = new Image("images/"+responseText);
image.setSize("300px", "300px");
grid.setWidget(0, 0, image);
}
public void onActionFailed(Form form, int httpStatus, java.lang.String responseText){
com.google.gwt.user.client.Window.alert("File upload is failed.");
}
});
this.add(grid);
}

}

Next step, create a servlet as code below:

package com.mycompany.project.servlet;

import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String rootDirectory = "C:/apache-tomcat-6.0.18/webapps/ImageViewer/";
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
FileItem item = (FileItem) iter.next();
if (item.isFormField()) {
} else {
String fileName = item.getName();
if (fileName != null && !fileName.equals("")) {
fileName = FilenameUtils.getName(fileName);
File uploadedFile = new File(rootDirectory+"images/"+fileName);
try {
item.write(uploadedFile);
response.getWriter().write(fileName);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
}

For this step you need to add commons-fileupload-1.2.1.jar and commons-io-1.4.jar to the project build path, and add the following code into web.xml:


<servlet>
<servlet-name>upload</servlet-name>
<servlet-class>com.mycompany.project.servlet.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>upload</servlet-name>
<url-pattern>/com.mycompany.project.ImageViewer/upload</url-pattern>
</servlet-mapping>

I advise you to create a folder name “images” in the root directory (war) to store uploaded files and don’t forget to update entry point class as follow:

public class ImageViewer implements EntryPoint {

public void onModuleLoad() {
RootPanel rootPanel = RootPanel.get();
Button clickMeButton = new Button();
rootPanel.add(clickMeButton);
clickMeButton.setText("Click me!");
clickMeButton.addClickHandler(new ClickHandler(){
public void onClick(ClickEvent event) {
FileUploadWindow window = new FileUploadWindow();
window.setVisible(true);
}
});
}
}

Finally compile the project, deploy it to apache tomcat server and have it a test, if there’s nothing wrong you must see the result as below

The source code download:
http://sharecash.org/download.php?file=464686

7 comments:

ankit said...

Hello sir you have given a wonderful tutorial of file uploading.

Sir I have a problem is that I am Unable to create a servlet into GWT project. I have searched a lot of on net "steps to add servlet into gwt project." but i fail to create a servlet into gwt project.

Ankit Jain said...

Sir now problem solved has been solved out. now i have done file upload project. and its working very good.

I want to sat thanks for a perfect tutorial. thank you ones again.

your fan

Ankit

Haydar said...

Hello sir,

Please may you add your files rapid. i couldn't down them.

RAS said...

Hello Sir,
Your code is very helpful & I'm able to work with it susscessfully in my GWT-Ext project. But now I need the same with SmartGWT project.
Can you help me?
Thanks.

Thomas Sadle said...

After Upload the file how it save. Can use a database with blob datatype (What if file too large?), Give some suggestions to save this file.?

madhavam.com said...

Sir ,
Please send me the source code of (file upload)FileUpload with GWT-Ext and java EE servlet..
My mailid is maluty567@gmail.com


Thanks

amit rana said...

Nice tutorial , I make Upload file on GXT it's work fine on running and debug mode but when i use my complied version first time when i click the browse button that uploading popup is not shown , after another click it is there but why not on first click. u can refer my code also on Stack overflow

http://stackoverflow.com/questions/12910358/gxt-upload-file-browse-

window-is-blocked-by-browser/12948378#12948378

Post a Comment