Tuesday, August 20, 2013

Upload file using widget in gwt ext

CLIENT CODE 

 example.java 
package com.client;

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.ui.Button;
import com.google.gwt.user.client.ui.RootPanel;
import com.gwtext.client.widgets.Window;

public class example 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);
    }
    });
    
    }
    }



FileUploadWindow.java
package com.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...", true);
}
}
});
}
}));
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("img/"+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);
}

}


SERVER CODE

XmlServlet.java

package com.server;


import java.io.*;

import java.sql.*;
import java.util.*;
import java.text.*;
import java.util.regex.*;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.*;
import org.mortbay.jetty.Response;

import javax.servlet.*;
import javax.servlet.http.*;

import java.io.*;   
import java.sql.*;   
import javax.servlet.http.HttpServlet;   
import javax.servlet.http.HttpServletRequest;   
import javax.servlet.http.HttpServletResponse;   
import javax.servlet.ServletInputStream.*;   
import java.io.PrintWriter;   
  
public class XmlServlet extends HttpServlet {   
  
public void doPost(HttpServletRequest req,HttpServletResponse res)   

    File uploadedFile;
  
    
    System.out.print("on server");
try{   
  
Class.forName("com.mysql.jdbc.Driver");   
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/image","root","enggheads");  

PrintWriter out=res.getWriter();   
  
//out.println("<br>Content type is :: " +contentType);   
//to get the content type information from JSP Request Header   
String contentType = req.getContentType();   
int flag=0;   
FileInputStream fis=null;   
FileOutputStream fileOut=null;   
//here we are checking the content type is not equal to Null and as well as the passed data from mulitpart/form-data is greater than or equal to 0   
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))   
{   
DataInputStream in = new DataInputStream(req.getInputStream());   
//we are taking the length of Content type data   
int formDataLength = req.getContentLength();   
byte dataBytes[] = new byte[formDataLength];   
int byteRead = 0;   
int totalBytesRead = 0;   
  
//this loop converting the uploaded file into byte code   
while (totalBytesRead < formDataLength) {   
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);   
totalBytesRead += byteRead;   
}   
  
String file = new String(dataBytes);   
//for saving the file name   
String saveFile = file.substring(file.indexOf("filename=\"") + 10);   
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));   
out.println("savefiledddd"+saveFile);   
int extension_save=saveFile.lastIndexOf("\"");   
String extension_saveName=saveFile.substring(extension_save);   
  
//Here we are invoking the absolute path out of the encrypted data   
  
saveFile = saveFile.substring(saveFile.lastIndexOf("\\")+ 1,saveFile.indexOf("\""));   
int lastIndex = contentType.lastIndexOf("=");   
String boundary = contentType.substring(lastIndex + 1,contentType.length());   
int pos;   
  
//extracting the index of file   
pos = file.indexOf("filename=\"");   
pos = file.indexOf("\n", pos) + 1;   
pos = file.indexOf("\n", pos) + 1;   
pos = file.indexOf("\n", pos) + 1;   
int boundaryLocation = file.indexOf(boundary, pos) - 4;   
int startPos = ((file.substring(0, pos)).getBytes()).length;   
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;   
  
out.println("savefile"+saveFile);   
  
int file_No=22;  

 uploadedFile=new File("./war/img");

    uploadedFile.mkdir();


  String kk=uploadedFile.getAbsolutePath();
  

  String pathname_dir=kk+"/"+saveFile;   
   //String pathname_dir="C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\jk\\"+saveFile;   
    File filepath=new File(pathname_dir);   
     out.println("filepath_  "+filepath);   
    fileOut = new FileOutputStream(filepath);   
    fileOut.write(dataBytes, startPos, (endPos - startPos));   
    fileOut.flush();   
    out.println("<h1> your files are saved</h1></body></html>");   
     out.close();   
  
         File database_filename=new File(pathname_dir);   
             fis=new FileInputStream(database_filename);   

int len=(int)database_filename.length();
             PreparedStatement ps = conn.prepareStatement("insert into new (image) values (?)");   
             ps.setBinaryStream(1,fis,len);   
             ps.executeUpdate();   
             ps.close();   
             flag=1;   
  
}   
  
if(flag==1)   
{   
fileOut.close();   
fis.close();   
}   
}catch(Exception e)   
{   
System.out.println("Exception Due to"+e);   
e.printStackTrace();   
}   
}   
}   


Required Four extra Jar File 
1) commons-fileupload-1.1.1
2)commons-io-1.4
3)mysql-connector-java-5.1.7-bin
4)gwtext 

No comments:

Post a Comment