Thursday, August 20, 2009

GWT - File Upload

I am trying to do file upload on GWT, I search through internet and unfortunately, I found no way of doing file uploads with RPC :-(

Solution i found still back to common HTTP upload, just tweak a little to fit into the GWT environment.
I post the solution here which mixed used of widget in GWT and GXT.
Please drop me a comment if you know of a better way, or way to improve what I have done.

GWT Part
1. FormPanel(GWT or GXT) must be used in order to upload.
2. Must set the Action by setAction();
3. Must set encoding to Encoding.Multipart;
4. Must use method POST;


final FormPanel formPanel = new FormPanel();
String action = GWT.getModuleBaseURL() + "uploadFile";
formPanel.setLabelWidth(150);
formPanel.setEncoding(Encoding.MULTIPART);
formPanel.setMethod(Method.POST);
formPanel.setAction(action);
formPanel.setFrame(true);
formPanel.setHeaderVisible(false);

// file upload field , set the name.
FileUploadField imageUploadField = new FileUploadField();
imageUploadField.setFieldLabel("Change Picture");
mageUploadField.setName("uplodapic");
formPanel.add(imageUploadField);

Button submitButton = new Button("Submit");
submitButton.addSelectionListener(new SelectionListener()
{
@Override
public void componentSelected(ComponentEvent ce)
{
formPanel.submit(); // call form submit for submit.
}
});

formPanel.addButton(submitButton);

formPanel.addFormHandler(new FormHandler()
{
public void onSubmitComplete(FormSubmitCompleteEvent 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());
}

public void onSubmit(FormSubmitEvent event)
{
// TODO Auto-generated method stub
}
});


Then add following lines to your XXXXX.gwt.xml

<servlet path="/uploadFile" class="com.server.FileUploadImpl"/>


Part 2 - Servlet
This servlet implementation used apache common file upload library and follow guide line in apache site.

public class FileUploadImpl extends HttpServlet
{
private static final long serialVersionUID = 8305367618713715640L;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/plain");
System.out.println("Inside File Upload Servlet...............>>>>>>>>>>");
try
{
getFileItem(request);
response.getWriter().write(new String("Uploading Completed...."));
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.getMessage());
}
}

private FileItem getFileItem(final HttpServletRequest request)
{
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
// Create a progress listener, if want to use
ProgressListener progressListener = new ProgressListener()
{
private long megaBytes = -1;
int i = -1;

public void update(long pBytesRead, long pContentLength, int pItems)
{
if(i != pItems)
{
i = pItems;
System.out.println("Setting TotalSize " + pContentLength);
System.out.println("We are currently reading item " + pItems);
}
long mBytes = pBytesRead / 10000;
if(megaBytes == mBytes)
{
return;
}
megaBytes = mBytes;
if(pContentLength == -1)
{
System.out.println("So far, " + pBytesRead + " bytes have been read.");
}
else
{
System.out.println("Read, " + pBytesRead + " of " + pContentLength + " bytes.");
}
}
};
upload.setProgressListener(progressListener);

try
{
List items = upload.parseRequest(request);
System.out.println("List Items, size --->" + items.size());
Iterator it = items.iterator();
while(it.hasNext())
{
FileItem item = (FileItem) it.next();
if(item.isFormField())
{
System.out.println("File String->" + item.getString());
}
else
{
System.out.println(String.format("File Name-> %s, Size-> %s, Content Type->%s, Isformfield-> %s, inMemory-> %s",
item.getFieldName(), item.getSize(), item.getContentType(), item.isFormField(), item.isInMemory()));
this.processUpload(item);
}
}
}
catch(Exception e)
{
e.printStackTrace();
System.out.println(e.toString());
return null;
}
return null;
}

private void processUpload(FileItem uploadItem)
{
try
{
InputStream input = uploadItem.getInputStream();
byte[] fileContents = uploadItem.get();
// TODO: add code to process file contents here.
// Process a file upload
/*
* if (writeToFile) {
* File uploadedFile = new File(...);
* item.write(uploadedFile);
* }
* else
* {
* InputStream uploadedStream =
* item.getInputStream();
* uploadedStream.close();
* }
*/
}
catch (IOException e)
{
e.printStackTrace();
}
}
}


So this should able to let you upload file from the GWT and process and the back end.

No comments: