Srikanth Technologies

Upload players photos into Oracle BLOB column and list players photos

In this post, I will show how to do the following tasks using Java EE 6.0. I have written a blog about the same a few years back when Java Servlets didn't provide any API for file upload. You can read that blog here, if you are using Java EE 5.0 or before.

Create web project and add libraries

First of all create a new web project - uploadblog, using NetBeans 7.1.1. I am using Tomcat 7. Add Oracle JDBC driver, ojdbc6.jar, to the project libraries.

Create PLAYERS table

Create a table in Oracle database as follows. This table contains id, which is unique for each photo, title of the photo and photo itself stored as BLOB.
 
create table players
( playername   varchar2(50) primary key,
  playerphoto  blob
);

Create HTML form to upload player's information

Create a HTML form to take data regarding a player. It contains a textbox for player name and file field to upload player’s photo.

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <h2>Add Player</h2>
        <form id="form1" enctype="multipart/form-data" action="addplayer" method="post">
            <table>
                <tr>
                    <td>Enter Player Name :</td>
                    <td><input  type="text"  name="playername"/></td>
                </tr>
                <tr>
                    <td>Select Photo  </td>
                    <td><input type="file"  name="playerphoto" />
                </tr>
            </table>
            <p/>
            <input type="submit" value="Add Photo"/>
        </form>
        <p/>
        <a href="listplayers">List Players</a>
    </body>
</html>




AddPlayerServlet

When user clicks on Submit button, the above form calls /addplayer, which is url pattern for AddPlayerServlet. The servlet inserts a row into PLAYERS table. The code for AddPlayerServlet.java is given below.

package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet(name = "AddPlayerServlet", urlPatterns = {"/addplayer"})
@MultipartConfig
public class AddPlayerServlet extends HttpServlet {

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
           
            Part p =  request.getPart("playername");
            Scanner scanner  = new Scanner( p.getInputStream());
            String playername = scanner.nextLine(); 
            
            
            Part photo =  request.getPart("playerphoto");
                        
           
            // Connect to Oracle
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
            con.setAutoCommit(false);

            PreparedStatement ps = con.prepareStatement("insert into players values(?,?)");
            ps.setString(1, playername);
            // size must be converted to int otherwise it results in error
            ps.setBinaryStream(2, photo.getInputStream(), (int)  photo.getSize());
            ps.executeUpdate();
            con.commit();
            con.close();
            out.println("Added Player Successfully. <p> <a href='listplayers'>List Players </a>");
        } 
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
        finally {            
            out.close();
        }
    }
}

ListPlayerServlet

ListPlayersServlet displays the list of players from PLAYERS table. It uses DisplayImageServelt to display each player's photo.
package servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ListPlayersServlet", urlPatterns = {"/listplayers"})
public class ListPlayersServlet extends HttpServlet {
    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
            PreparedStatement ps = con.prepareStatement("select * from players");
            ResultSet rs = ps.executeQuery();
            out.println("<h1>Players</h1>");
            while ( rs.next()) {
                  out.println("<h3>" + rs.getString("playername") + "</h3>");
                  out.println("<img width='300' height='300' src=displayphoto?name=" +  rs.getString("playername") + "></img> <p/>");
            }
            con.close();
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
        
        finally {            
            out.close();
        }
    }
}

DisplayPhotoServlet

DisplayPhotoServlet sends a single player's photo that is stored in PLAYERPHOTO column of PLAYERS table to browser's outputstream. This servelt takes playername as parameter.
package servlets;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "DisplayPhotoServlet", urlPatterns = {"/displayphoto"})
public class DisplayPhotoServlet extends HttpServlet {

    @Override 
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
            Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr");
            PreparedStatement ps = con.prepareStatement("select playerphoto from players where playername = ?");
            String name = request.getParameter("name");
            ps.setString(1,name );
            ResultSet rs = ps.executeQuery();
            rs.next();
            Blob b = rs.getBlob("playerphoto");
            response.setContentType("image/jpeg");
            response.setContentLength((int) b.length());
            InputStream is = b.getBinaryStream();
            OutputStream os = response.getOutputStream();
            byte buf[] = new byte[(int) b.length()];
            is.read(buf);
            os.write(buf);
            os.close();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }

}

After all servlets are created, build the project and deploy it. Then run addplayer.html and enter details of a player. Use List Players link to see the list of players names and their photos that are stored in the database.


Post Your Comment

Image

Enter the code given in the above image :
Enter Your Name :
Enter Your Email Address :
Enter Your Comment :

Comments


Posted By Ranjith On 15-Nov-12 02:37:46 PM

Sir, i had referred to code , its working for only 2k-4k size of photo , if i upload a size of 19k , its throwing a error message , please guide to how to upload a photo



Posted By Ranjith On 27-Nov-12 03:05:33 PM

this code doesnt not upload the image which is having a size of more than 14k

plz help me



Posted By Vamsi Sangam On 01-Jul-14 01:24:20 PM

It works like magic!..... Uploaded and displayed an Image of 223KB, with no issues! Thanks a lot, Sir....!



Posted By vamsi On 08-Feb-15 07:42:01 PM

sir i am getting null poiter exception please explain....



Posted By Vinod On 08-Apr-15 12:34:15 AM

Thanks for the code
It is working good for me



Posted By khushbu On 09-Nov-15 12:38:39 PM

sir i have made a web based project using JSPs and servlets where i am fetching few details from database like username password n other user info but now i want to put few images in the UI of my project for which i have already stored 3-4 blob images in the database but i am not able to find out that how these images will b fetched from database and put in the UI of the project.please help me..