Upload photos into Oracle BLOB column from Java Servlet and listing photos

In this post, I will show how to do the following tasks using Java.

Create web project and add libraries

First of all create a new web project and add the following libraries to it. I named the project as photos. You can give any name to the project. I am using NetBeans IDE 6.5 for this example. You can use any IDE of your choice and any version of NetBeans.

Create PHOTOS 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 photos
  ( 
    id  number(5) primary key,
    title  varchar(50),
    photo  blob
  );

Download Commons-Fileupload library

As we have to deal with File upload, we need to use apaches commons-fileupload library. This library dependes on commons-io library. So, we need to download both these libraries from commons-fileupload and commons-io.

After you download these libraries, add .jar files to project using libraries node in NetBeans project window. Do whatever is necessary to include these libraries if you are using other IDEs other than NetBeans.

Create HTML form to upload photo

Create a HTML form to take data regarding a new photo. It contains two text fields and one file field to upload photo to server.
 <html>
    <head>
        <title>Add Photo</title>
    </head>
    <body>
        <h2>Add Photo</h2>
        <form id="form1" enctype="multipart/form-data" action="addphoto" method="post">
            <table>
                <tr>
                    <td>Enter Photo Id :</td>
                    <td><input  type="text"  name="id"/></td>
                </tr>
                <tr>
                    <td>Enter Title For Photo :</td>
                    <td><input  type="text"  name="title"/></td>
                </tr>
                <tr>
                    <td>Select Photo  </td>
                    <td><input type="file"  name="photo" />
                </tr>
            </table>
            <p/>
            <input type="submit" value="Add Photo"/>
        </form>

        <p/>
        <a href="listphotos">List Photos </a>
    </body>
</html>

AddPhotoServlet

When user clicks on Submit button, the above form calls AddPhotoServlet, which inserts a row into PHOTOS table. The code for AddPhotoServlet.java is given below. Create this servelt and assign addphoto as the url pattern for it.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class AddPhotoServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            // Apache Commons-Fileupload library classes
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload sfu  = new ServletFileUpload(factory);

            if (! ServletFileUpload.isMultipartContent(request)) {
                System.out.println("sorry. No file uploaded");
                return;
            }

            // parse request
            List items = sfu.parseRequest(request);
            FileItem  id = (FileItem) items.get(0);
            String photoid =  id.getString();
            
            FileItem title = (FileItem) items.get(1);
            String   phototitle =  title.getString();

            // get uploaded file
            FileItem file = (FileItem) items.get(2);
                        
            // 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 photos values(?,?,?)");
            ps.setString(1, photoid);
            ps.setString(2, phototitle);
            // size must be converted to int otherwise it results in error
            ps.setBinaryStream(3, file.getInputStream(), (int) file.getSize());
            ps.executeUpdate();
            con.commit();
            con.close();
            out.println("Proto Added Successfully. <p> <a href='listphotos'>List Photos </a>");
        }
        catch(Exception ex) {
            out.println( "Error --> " + ex.getMessage());
        }
    } 
}

ListPhotosServlet

Create another servlet - ListPhotosServlet.java - to display the list of photos from PHOTOS table. It uses DisplayImageServelt to display each photo.
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.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ListPhotosServlet extends HttpServlet {
   
    protected void processRequest(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 photos");
            ResultSet rs = ps.executeQuery();
            out.println("<h1>Photos</h1>");
            while ( rs.next()) {
                  out.println("<h4>" + rs.getString("title") + "</h4>");
                  out.println("<img width='600' height='600' src=displayphoto?id=" +  rs.getString("id") + "></img> <p/>");
            }

            con.close();
        }
        catch(Exception ex) {

        }
        finally { 
            out.close();
        }
    } 

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

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

DisplayPhotoServlet

DisplayPhotoServlet.java sends a a single photo that is taken from PHOTO column of PHOTOS table to browser as outputstream. This servelt takes id as parameter (querystring) and send photo to IMG tag.

DisplayPhotoServlet.java

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DisplayPhotoServlet extends HttpServlet {
    protected void processRequest(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 photo from photos where id = ?");
            String id = request.getParameter("id");
            ps.setString(1,id);
            ResultSet rs = ps.executeQuery();
            rs.next();
            Blob  b = rs.getBlob("photo");
            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());
        }
    } 

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

Here is web.xml file that contains entries related to Servlets.
    <servlet>
        <servlet-name>AddPhoto</servlet-name>
        <servlet-class>AddPhotoServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>ListPhotos</servlet-name>
        <servlet-class>ListPhotosServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>DisplayPhotoServlet</servlet-name>
        <servlet-class>DisplayPhotoServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>AddPhoto</servlet-name>
        <url-pattern>/addphoto</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>ListPhotos</servlet-name>
        <url-pattern>/listphotos</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>DisplayPhotoServlet</servlet-name>
        <url-pattern>/displayphoto</url-pattern>
    </servlet-mapping>


After all servlets are created, build the project and deploy it. Then run addphoto.html and enter details of some photos. Then you can click on List Photos link to see the list of photos placed in the database.



Home    Blogs

Post Your Comment

Image

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

Comments


Posted By sachidanandam On 07-Aug-09 06:42:35 AM

while adding photos into a oracle database iam receiving class,enum or interface exception (or) packet failure exception is handled how to resolve this ......plz help me



Posted By Emmanuel On 13-Aug-09 06:40:39 PM

Hi, this is a perfect post.... It works perfectly! Thank you for this.



Posted By sachidanandam On 16-Aug-09 06:21:39 AM

what is thin and xe refers to............



Posted By saswata banerjee On 09-Sep-09 11:42:37 AM

it's really very amazing..but i have a new idea.if u want to know that plz contact me...



Posted By bayardalai On 01-Oct-09 10:19:22 AM

Hi, thanks for all your scripts, but!!! didn't find addphoto after i done everything. other mean is can't find AddPotoServlet class. I put my all servlet to package called FileUpload. Please, anyone does know abot it



Posted By uuree On 05-Oct-09 09:51:54 AM

Hi, all. I done everythng succesfully. So to bayardalai: put web.xml file to webroot/web-inf if you are using myeclipse 6.5. put all servlets to what you greated package. That's it. Don't forget point your package directory in your web.xml file if didn't find addphoto just like FileUpload.AddPhotoServlet.



Posted By kamal On 07-Oct-09 12:43:24 AM

is it possible to perform all these three operations using one servlet ,instead of uing three .



Posted By kamal On 14-Oct-09 11:31:11 PM

is there any way to restrict any way to restrict the users to upload the files greater than specified size.



Posted By ravi On 23-Jun-10 07:13:54 AM

update statement wont work.following same code as insert. plz help me out.
PreparedStatement ps = con.prepareStatement("update photos set id=?,title=?,product_id=?,photos=?");



Posted By Sanjeev On 30-Jul-10 03:58:19 PM

Good information. Really appreciate the work. Kepp the good work going!!! I ll try out some...



Posted By Saurabh Kakkar On 03-Nov-10 03:19:24 PM

Best post....
i was trying this for 2 days and i finally did this with a great help from this post...

kudos to the uploader...



Posted By mani On 02-Dec-10 06:56:31 AM

can we upload ms word document instead of photos??



Posted By sravan kumar On 14-Feb-11 05:50:44 PM

i am searching for this type model code to store and retrive photos in web pages from last 3 months.But i really satisfied by the code provided here.



Posted By ag On 21-May-11 10:16:47 PM

It generates error ORA-01460: unimplemented or unreasonable conversion requested.
How can I solve this problem??? Maybe you can show me some tips, to implement this application properly. plz help me



Posted By sreekanth On 01-Sep-11 07:03:48 PM

Thanq....



Posted By srikanth On 08-Sep-11 05:27:32 PM

I am getting NullPointerException at Blob b = rs.getBlob("photo"); in DisplayphotoServlet. please could you tel me the reason its urgent..



Posted By Vivek On 30-Sep-11 03:00:08 PM

Excellent - thanks it really helped me understand the process.



Posted By Avinash On 06-Oct-11 11:23:07 PM

Respected Sir,

I want to store the images in online store project but this code have error

in the following part of the code:


// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);

if (! ServletFileUpload.isMultipartContent(request)) {
System.out.println("sorry. No file uploaded");
return;
}

// parse request
List items = sfu.parseRequest(request);
FileItem id = (FileItem) items.get(0);
String photoid = id.getString();

FileItem title = (FileItem) items.get(1);
String phototitle = title.getString();

// get uploaded file




So please help me. I will be very thakful to you.

Yours Faithfully
Avinash



Posted By wenky On 23-Oct-11 12:36:41 AM

I got this error when i click submit button..plz help me
I hav changed the databse username nd password too..
Error --> Io exception: Connection refused(DESCRIPTION=(TMP=)(VSNNUM=169869568)(ERR=12505)(ERROR_STACK=(ERROR=(CODE=12505)(EMFI=4))))



Posted By ankur On 30-Oct-11 02:22:49 PM

this is good simple coding
keep it up



Posted By Sally On 23-Nov-11 03:22:41 AM

I am getting an ORA-01460 error...I have narrowed it down to the picture upload portion...the ps.setBinaryStream(...)....Why is this happening? Help!



Posted By raj On 28-Nov-11 11:36:44 PM

i am trying to run the above code but it is showing errors common files are "can not find " . i added common upload files into my lib folder



Posted By ravi On 15-Jan-12 10:00:03 PM

please, help me code is working perfectly, but when i'm trying to show image, then images are not displaying. Also, images are not storing into the database. Plz, help me !! URGENT



Posted By praveen kumar On 22-Jan-12 11:14:48 PM

thanks...
it's very helpfull



Posted By AntonioMU On 08-Feb-12 04:07:07 PM

excelent, this article is 100 % functional. thanks and regards



Posted By Vivek On 11-Feb-12 12:26:39 AM

Guys, i am getting this error after writing the same code. Please help me it is urgent.

Error --> ORA-01460: unimplemented or unreasonable conversion requested

I request the admin and the other associates to please help me with a solution



Posted By amit On 21-Jun-12 05:26:01 PM

the mystry ended which i face last 3-4 months.
thank you very much sir...



Posted By Hardip On 05-Jul-12 08:45:19 PM

hey i am using glassfish instead of apache. so can u tell me where i can get the file upload jar files as such for apache...



Posted By Ruchi On 05-Oct-12 02:24:12 PM

hi, I am not gettinh any thing.It shows page not found i am using NetBeansIDE 7.0.
Can anyone please help me out that how could i get the right output.



Posted By mohan On 25-Oct-12 12:40:58 PM

my code is same as like this but i didn't get different images,instead of different images it display the first image multiple times.please help me how can retrieve different images using same code



Posted By GmA On 21-Nov-12 05:17:38 PM

Great code - works very well - very easy to deploy



Posted By partha On 14-Dec-12 12:33:35 AM

Please help me. I am getting Error --> ORA-01460: unimplemented or unreasonable conversion requested. How to solve it



Posted By Arun verma On 01-Jan-13 06:26:49 PM

when i click on upload in jsp page it gives an internal error in executing servlet.please tell me



Posted By Rajat On 09-Feb-13 02:34:43 PM

But it is not showing the image file.It shows as a broken image file.How to correct it?



Posted By Girish On 31-Mar-13 10:32:21 PM

u requested from servlet to servlet and pictures are displayed in the servlet only using html tag.
But how to request from jsp and get images from servlet



Posted By DeePHeaRT Co. On 16-Jun-13 04:50:06 PM

work just fine. lol. tq



Posted By Sarat Majhi On 18-Sep-13 07:38:52 PM

Hi all ..This is a very good post and all are functional.I want to insert DATE INFO into Oracle table in date field. can any body help me in this regard.Thanks in advance.



Posted By Ravindra On 28-Oct-13 09:13:35 AM

Hi

Example give above is very useful and simple. its works fine for me.

I'm implementing website for my village but i have very less knowledge with uploading images and displaying them so can you help me in this topic...

I'm using MVC(servlet and jsp's) with hibernate and eclipse IDE.

can anybody give me link or project which includes, Uploading and displaying images by using servlet, jsp and Hibernate.

Thank you



Posted By shweta On 12-Mar-14 10:25:58 AM

photos are added in my database but they are not displayed using above servlet code.I used same code as above what could be the problem?



Posted By prasanth Srinivasan On 20-Mar-14 04:44:21 PM

Hi sir
i read all your tutorials i want to upload image by browsing and save it in oracle using java swing with jdbc connection could you please post a program for that.thank you so much in advance.



Posted By Ravi On 04-Apr-14 07:02:11 PM

Sir it works fine.
But i want to store multiple images in db in this post only one image stores in db
please help me



Posted By kumar On 29-Aug-14 05:27:38 PM

It's a perfect tutorial for this concept,i searched google more i didn't got the correct answer,it's very helpful to us,thanks for this tutorial.



Posted By Moises On 03-Sep-14 04:54:50 AM

Wonderful, it works. Thank you so much.

Copyright © Srikanth Technologies. All rights reserved.