Wednesday, March 17, 2010

File Upload from Flex to Mysql Database:-Java Part

      Today I am going to describe how to insert the uploaded file in to Mysql database.For this we need apache fileupload jar files commons-fileupload-1.2.1.jar and commons.io-1.4.jar. . You can download the latest version of the package from http://commons.apache.org/downloads/download_fileupload.cgi.
Now first I am writing a class file

FileUploadListner.java

package servlet;

import org.apache.commons.fileupload.ProgressListener;


public class FileUploadListener implements ProgressListener
{
    private volatile long
      bytesRead = 0L,
      contentLength = 0L,
      item = 0L;  
   
    public FileUploadListener()
    {
      super();
    }
   
    public void update(long aBytesRead, long aContentLength, int anItem)
    {
        bytesRead = aBytesRead;
        contentLength = aContentLength;
        item = anItem;
    }
   
    public long getBytesRead()
    {
        return bytesRead;
    }
   
    public long getContentLength()
    {
        return contentLength;
    }
   
    public long getItem()
    {
        return item;
    }
}


Now I am writing a servlet which will insert the file into database.

MyUploadServlet.java

package servlet;
import DBConnection;
import javax.servlet.http.HttpServlet;
import javax.servlet.Servlet;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.sql.*;    
public class MyUploadServlet extends HttpServlet implements Servlet
{   
    private String filename;
    public MyUploadServlet()
    {
        super();
    }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
doPost(request,response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        DBConnection con=new DBConnection();
    PrintWriter ptr=response.getWriter();
    String jnan="";
// create file upload factory and upload servlet
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        // set file upload progress listener
        FileUploadListener listener = new FileUploadListener();
        HttpSession session = request.getSession();
        session.setAttribute("LISTENER", listener);       
        // upload servlet allows to set upload listener
        upload.setProgressListener(listener);
        List uploadedItems = null;
        FileItem fileItem = null;       
         try
        {
            // iterate over all uploaded files
            uploadedItems = upload.parseRequest(request);
            Iterator i = uploadedItems.iterator();
            String str1[]={"","","","","","","","","","","","",""};
            int cc=0;
            while (i.hasNext())
            {       
                fileItem = (FileItem) i.next();
                if(fileItem.isFormField() == true&&cc!=2)
                {
                jnan=String.valueOf(fileItem);
                jnan=jnan.substring(jnan.indexOf("FieldName=")+10,jnan.length());
                str1[cc]=jnan;
                cc++;
            }
               
        if (fileItem.isFormField() == false)
{           
            if (fileItem.getSize() > 0)
            {
                File uploadedFile = null;
                String myFullFileName = fileItem.getName(),
                myFileName = "",
                slashType = (myFullFileName.lastIndexOf("\\") > 0) ? "\\" : "/"; // Windows or UNIX
                int startIndex = myFullFileName.lastIndexOf(slashType);
//Get File Name
myFileName = myFullFileName.substring(startIndex + 1, myFullFileName.length());
//Get File Extension
                String fileExt=myFileName.substring(myFileName.indexOf("."),myFileName.length());           
// Create new File object
                       
try{
ByteArrayInputStream bs=new ByteArrayInputStream(fileItem.get());
String query="INSERT INTO image(img) VALUES(?)";
PreparedStatement pst=con.conn.prepareStatement(query);
pst.setBinaryStream(1, bs,(int)fileItem.getSize());
pst.execute();
}
catch(Exception e)
{
System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
}
}
                       
                }
           
            }
        }
        catch (FileUploadException e)
        {
            System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
        }
        catch (Exception e)
        {
            System.out.println("in MyUploadServlet..Error:- "+e.getMessage());
        }
        finally
        {
            con.DisconnectCon();
        }
    }      
}
Here DBConnection is a class file.I am using this class to connect to mysql database from my eclipse.I made a connection pooling from apache tomcat 5.5 to Mysql.This class file is given below.
DBConnection.java:-

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBConnection {
  
    private javax.naming.Context ic;
    private javax.sql.DataSource ds;
    public java.sql.Connection conn;
      
    public DBConnection()
    {
        try
        {

            ic=(Context)new InitialContext().lookup("java:comp/env");
            ds=(DataSource)ic.lookup("jdbc/MyJndiName");
            conn=ds.getConnection();
        }
        catch(Exception e)
        {
            System.out.println("Error in DBConnection "+e.getMessage());
        }
    }
    public void DisconnectCon()
    {
        try
        {
            conn.close();
        }
        catch(Exception e)
        {
            System.out.println("Error in DisconnectCon "+e.getMessage());
        }
    }
}
Done....The file is there in Database...
Thanks
Now We need to display the file from database into the flex RIA...I mean we have to Create an Image gallery in Flex!!! Comming Next

1 comment:

  1. This comment has been removed by the author.

    ReplyDelete