Wednesday, April 17, 2013

How to insert an image in Oracle through Servlet


Hi all,

In this post i will tell you how to insert image in a database (Oracle) through a Servlet.

First of all make a table in Oracle named "image_master" having three fields i.e id, name, image.

Step 1:- Creating table in database.
just copy / paste the code in oracle SQL command line:-
CREATE TABLE  "IMAGE_MASTER" 
   ( "ID" NUMBER NOT NULL ENABLE, 
 "NAME" VARCHAR2(40), 
 "IMAGE" BLOB, 
  CONSTRAINT "IMAGE_MASTER_PK" PRIMARY KEY ("ID") ENABLE
   )

Step 2:- Create a Servlet for inserting image.
Now after creating the table, make a servlet named "InsertImage" which extends HttpServlet and overrides doGet() and doPost() method.

package others;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;

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

public class InsertImage extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            /**
             * make a database connection. Here we are making connection with oracle database.
             * for Oracle Type-4 driver:-
             * Driver Class = ("oracle.jdbc.driver.OracleDriver")
             * Connection String = ("jdbc:oracle:thin:@localhost:1521:xe","user_name","password")
             */
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "oralce");
            /**
             * making an object of FileInputStream for reading the image file in form of bytes.
             * path of the file is provided as an argument.
             */
            FileInputStream fis = new FileInputStream("c:/images/hello.jpg");
            PreparedStatement st = con.prepareStatement("insert into image_master values(?,?,?)");
            st.setInt(1, 1001);
            st.setString(2, "Prakash");
            /**
             * method setBinaryStream() is used for inserting image in database.
             */
            st.setBinaryStream(3, fis, fis.available());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}

Step 3:- Making web.xml entry:-
imageServlet 
servlets/ImageServlet

No comments :

Post a Comment