gwtupload custom package with example/sample application

UPDATED: 14 October 2013
Uploading file(s) on the server is always important part of any web application. Today we are talking about uploading file(s) in GWT application along with the progress bar. Before we begin lets have look at the source of this plugin.


gwtupload
Its originally coded by "Manolo Carrasco". I made few changes regarding maximum upload size in original source code. The plugin works fine but when you want dynamic upload size for your each uploader. This facility not provided in current version. By using my custom gwtupload plugin you'll have that flexibility.

Prerequisites (Available in sample application)
1. gwtupload-custom.jar
2. commons-fileupload-1.2.2.jar
3. commons-io-2.3.jar
4. log4j-1.2.15.jar

I attached sample project at the end of the article. Lets have look at the important snippet of code...

GwtuploadSample.java
package com.javaquery.client;

import gwtupload.client.IFileInput.FileInputType;
import gwtupload.client.IUploadStatus.Status;
import gwtupload.client.IUploader;
import gwtupload.client.IUploader.OnChangeUploaderHandler;
import gwtupload.client.IUploader.OnFinishUploaderHandler;
import gwtupload.client.IUploader.OnStartUploaderHandler;
import gwtupload.client.MultiUploader;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.ui.Hidden;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;

/**
 * Entry point classes define onModuleLoad().
 */
public class GwtuploadSample implements EntryPoint {
 /**
  * This is the entry point method.
  */
 public void onModuleLoad() {
  final Label responseLabel = new Label();
  
  MultiUploader multiUploader = new MultiUploader(FileInputType.BUTTON);
  multiUploader.setAutoSubmit(true);
  multiUploader.setEnabled(true);
  multiUploader.avoidRepeatFiles(false);
  multiUploader.addOnChangeUploadHandler(new OnChangeUploaderHandler() {
   @Override
   public void onChange(IUploader uploader) {
    if(uploader.getStatus() == Status.CHANGED){
     System.out.println("File input changed, can be handled before upload begin");
     /**
      * If you want to validate something at your side before upload.  
      * Check it here and you can cancel uploading.
      * Uncomment below line if you need it.
      * /
      
     /* uploader.cancel(); */
    }
   }
  });
  multiUploader.addOnStartUploadHandler(new OnStartUploaderHandler() {
   @Override
   public void onStart(IUploader uploader) {
    /**
     * This is where you can pass the hidden value to servlet.
     */
    uploader.add(new Hidden("param1", "value"));
    uploader.add(new Hidden("param2", "value"));
   }
  });
  multiUploader.addOnFinishUploadHandler(new OnFinishUploaderHandler() {
   @Override
   public void onFinish(IUploader uploader) {
    /**
     * Before processing output check the status of upload.
     */
    if(uploader.getStatus() == Status.SUCCESS){
     /**
      * If you passed details in JSONObject. You have to use subtring function of String to get your JSON String.
      */
     System.out.println(uploader.getServerResponse());
     responseLabel.setText(uploader.getServerRawResponse());
    }else{
     System.out.println(uploader.getStatus());
    }
   }
  });  
  //10485760 = 10 MB x 1024 x 1024
  multiUploader.setServletPath(GWT.getModuleBaseURL()+"upServlet?maxUpload=10485760");
  
  // Add the nameField and sendButton to the RootPanel
  // Use RootPanel.get() to get the entire body element
  RootPanel.get("MultiUpload").add(multiUploader);
  RootPanel.get("infoLabel").add(responseLabel);
 }
}

uploadServlet.java
package com.javaquery.server;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;

import gwtupload.server.UploadAction;
import gwtupload.server.exceptions.UploadActionException;

public class uploadServlet extends UploadAction{
 private static final long serialVersionUID = -4035393951562844790L;

 @Override
 public String executeAction(HttpServletRequest request, List sessionFiles) throws UploadActionException {
  String response = "";
  for (FileItem item : sessionFiles) {
   if (false == item.isFormField()) {
    String fileNameWithExt = item.getName();
    String fileName = fileNameWithExt.substring(0, fileNameWithExt.lastIndexOf("."));
    String fileExt = fileNameWithExt.substring(fileNameWithExt.lastIndexOf("."), fileNameWithExt.length());
    String uploadDir = getServletContext().getRealPath("/") + "gwtuploadFiles" + File.separatorChar;
    try {
     /**
      * Creating temporary file at "C:\Users\javaQuery\AppData\Local\Temp"
      * File.createTempFile(arg1,arg2)
      * arg1 : prefix you want to set. 
      *      Why "_projectName" used?
      *      - Say if filename length is 2 character then it'll throws error. 
      *        So for safe side we added "_projectName" to ensure that it must be long name.
      * arg2 : postfix you want to set. Whether its and extension or anything you like
      */
     File tempFile = File.createTempFile(fileName+"_projectName", ".bin");
     item.write(tempFile);

     /**
      * Before writing file to server folder you can scan temporary file (with antivirus on server) if you want.
      * Write it to server at your desired location. 
      */
     File createDir = new File(uploadDir);
     if (!createDir.exists()) {
      createDir.mkdir();
     }
     File saveOnserver = new File(uploadDir + File.separatorChar + item.getName());
     /**
      * Copy temporary file to original file.
      */
     FileInputStream inStream = new FileInputStream(tempFile);
     FileOutputStream outStream = new FileOutputStream(saveOnserver);
     byte[] buffer = new byte[1024];
     int length;
     while ((length = inStream.read(buffer)) > 0) {
      outStream.write(buffer, 0, length);
     }
     inStream.close();
     outStream.close();
     
     /**
      * Set response message you want at client side.
      * Say if you want extended details of your upload. Create JSON object, put values in it and pass it as String.
      */
     response += "File saved as " + saveOnserver.getAbsolutePath();
    } catch (Exception e) {
     throw new UploadActionException(e);
    }
   }else{
    /**
     * You can get the other parameter of your request here.
     */
    String hiddenFieldName = item.getFieldName();
    String hiddenFieldValue = item.getString();
    System.out.println("{param: "+hiddenFieldName+"; value: "+hiddenFieldValue+"}");
   }
  }

  // Remove files from session because we have a copy of them
  removeSessionFileItems(request);

  // Send your customized message to the client.
  return response;
 }
}

web.xml
<web-app version="2.5" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemalocation="http://java.sun.com/xml/ns/javaee 
              http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
 
  <servlet>
    <servlet-name>uploadServlet</servlet-name>
    <servlet-class>com.javaquery.server.uploadServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>uploadServlet</servlet-name>
    <url-pattern>/gwtuploadsample/upServlet</url-pattern>
  </servlet-mapping>
  
  <!-- Default page to serve -->
  <welcome-file-list>
    <welcome-file>GwtuploadSample.html</welcome-file>
  </welcome-file-list>

</web-app>

Now you are good to go for multiple file upload in GWT with progress bar. Don't forget to check official project website. For any queries and latest updates.

Download Sample Application

0 comments :