Saturday 16 March 2013

GWT File uploading and save it to DB


File uploading in GWT, and save it to DB

How to create an app to host in google appspot.com, which provides to upload file and show it upone request from client side. Kind of tricky things to develop some diffrent apps :), we too found it will help to develop some good apps, so decided to post how we done it  by using jdo.

4 steps todo it.

STEP 1:

Create an app and add commons-fileupload-1.2.2.jar and commons-io-1.4.jar to project build path.

STEP 2:

In server side:

  1.  Create a Persistance Manager Factory provider class "PMF.java"
  2.  Create a file storing entity class "WaterTalkFiles.java"
  3.  Create file uploader service name it "WaterTalkUploadService.java"
---------------------------------------------------------PMF.java----------------------------------------------------------
package com.de.watertalks.server;

import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;

public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper.getPersistenceManagerFactory("transactions-optional");//"transactions-optional"

private PMF() {
}

public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
----------------------------------------------------WaterTalkFiles.jav------------------------------------------------
package com.de.watertalks.server;

import javax.jdo.annotations.IdentityType;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Blob;

@PersistenceCapable(identityType = IdentityType.APPLICATION)
public class WaterTalkFiles {
@PrimaryKey
String filename;
Blob data;
public WaterTalkFiles(String fname,byte[] b){
filename = fname;
data = new Blob(b);
}
}
-------------------------------------------WaterTalkUploadService.java----------------------------------------

package com.de.watertalks.server;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

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

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@SuppressWarnings("serial")
public class WaterTalkUploadService extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletFileUpload upload = new ServletFileUpload();

try {
FileItemIterator iter = upload.getItemIterator(request);

while (iter.hasNext()) {
FileItemStream item = iter.next();

String name = item.getFieldName();
InputStream stream = item.openStream();

// Process the input stream
ByteArrayOutputStream out = new ByteArrayOutputStream();
int len;
byte[] buffer = new byte[8192];
while ((len = stream.read(buffer, 0, buffer.length)) != -1) {
out.write(buffer, 0, len);
}
//save file
WaterTalkFiles file = new WaterTalkFiles(name, buffer);
PersistenceManager pm = null;
             try {
                    pm = PMF.get().getPersistenceManager();
                    javax.jdo.Transaction transaction = pm.currentTransaction();
                    transaction.begin();
                    WaterTalkFiles guest = new WaterTalkFiles(name,buffer);
                    pm.makePersistent(guest);
                    transaction.commit();
             } catch (Exception e) {
                    e.printStackTrace();
             } finally {
                    if (null != pm)
                          pm.close();
             }
}
} catch (Exception e) {
throw new RuntimeException(e);
}

}
}



STEP 3:


  • In client side, create file uploading composite component class "WaterTalksFileUploadingComponent.java"


package com.de.watertalks.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FileUpload;
import com.google.gwt.user.client.ui.FormPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class WaterTalksFileUploadingComponent extends Composite{

final FormPanel form = new FormPanel();
VerticalPanel vPanel = new VerticalPanel(); 
FileUpload fileUpload = new FileUpload();
Label maxUpload =new Label();
 
public WaterTalksFileUploadingComponent(){

form.setMethod(FormPanel.METHOD_POST);
   form.setEncoding(FormPanel.ENCODING_MULTIPART); //  multipart MIME encoding
   form.setAction("/FileUploadByWaterTalks"); // The servlet FileUploadGreeting
   form.setWidget(vPanel);
   fileUpload.setName("uploader"); // Very important    
   vPanel.add(fileUpload);    
   maxUpload.setText("Maximum upload file size: 1MB");
   vPanel.add(maxUpload);
   vPanel.add(new Button("Submit", new ClickHandler() {
       public void onClick(ClickEvent event) {
               form.submit();
       }
   }));
   initWidget(form);

}
}




STEP 4: 

Add the following snippet to web.xml in 

<!-- de-water-talks file uploader service -->
<servlet>
 <servlet-name>
  FileUploadByWaterTalks
 </servlet-name>
 <servlet-class>
  com.de.watertalks.server.WaterTalkUploadService
 </servlet-class>
 </servlet>
 <servlet-mapping>
 <servlet-name>
  FileUploadByWaterTalks
 </servlet-name>
 <url-pattern>
  /FileUploadByWaterTalks
 </url-pattern>
</servlet-mapping>


Now create an instance of file uploader component you created and add it  to proper location in your module and run the onModule class. So far uploading is compleate. Now downloading :) Will our next post.





3 comments:

  1. As I am new to GWT, I am not able to decide where should I create an instance of file upload component. Please explain in detail about creation of instance of file upload component.

    ReplyDelete
    Replies
    1. In a class that implements EntryPoint interface, which has a onModuleLoad() method. Create the object in it and call with the RootPanel

      Delete
  2. Thanks so much!!!!! Great Work!!!

    ReplyDelete