Thursday 21 July 2011

File Upload using smart gwt

 FileUploadsmart.java
package com.client;

import com.shared.FieldVerifier;
import com.smartgwt.client.types.Encoding;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.form.DynamicForm;
import com.smartgwt.client.widgets.form.fields.HiddenItem;
import com.smartgwt.client.widgets.form.fields.TextItem;
import com.smartgwt.client.widgets.form.fields.UploadItem;
import com.smartgwt.client.widgets.layout.VLayout;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.smartgwt.client.widgets.form.fields.FormItem;
import com.smartgwt.client.widgets.form.fields.LinkItem;


public class FileUploadsmart implements EntryPoint {

  private static final String SERVER_ERROR = "An error occurred while "
      + "attempting to contact the server. Please check your network "
      + "connection and try again.";

 
  private final GreetingServiceAsync greetingService = GWT.create(GreetingService.class);

 
  public void onModuleLoad() {
     
     // String url =GWT.getModuleBaseURL()+"upload";
 
 

        VLayout layout = new VLayout();
        layout.setSize("100px", "44px");
       
        final DynamicForm uploadForm = new DynamicForm();       
        uploadForm.setSize("54px", "147px");
        uploadForm.setEncoding(Encoding.MULTIPART);
       
       
          UploadItem fileItem = new UploadItem("image");
       
         // fileItem.setShouldSaveValue(true);
        //  fileItem.setShowDisabled(false);
        //  fileItem.setShowHint(false);
        //  fileItem.setShowTitle(false);
         
          
        uploadForm.setAction(GWT.getModuleBaseURL()+"upload");
        IButton uploadButton = new IButton("Attachment");
        uploadButton.addClickHandler(new com.smartgwt.client.widgets.events.ClickHandler()
        {
            @Override
            public void onClick(
                    com.smartgwt.client.widgets.events.ClickEvent event) {
                // TODO Auto-generated method stub
                uploadForm.submitForm();
            }
        });
           
    uploadForm.setItems(fileItem);
       
        layout.setMembers(uploadForm, uploadButton);

       
       
       
        RootPanel.get().add(layout, 2, 2);
    }
}




Servlet Mapping in web.xml


 <servlet>
   <servlet-name>upload</servlet-name>
   <servlet-class>com.server.FileUploadServlet</servlet-class>
 </servlet>


 <servlet-mapping>
   <servlet-name>upload</servlet-name>
   <url-pattern>/ FileUploadsmart/upload</url-pattern>
 </servlet-mapping>
 








Server
  FileUploadServlet.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 FileUploadServlet 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;  
}  
 
res.setContentType("application/octet-stream");
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();  
}  
}  
}  
 


No comments:

Post a Comment