December 19, 2010

Insert and Display image BLOB in JSP page

Hi everyone,

Today we just tried to insert jpeg file and displaying that file in one html page

Source Code:
file name: img_uploadanddisplay.jsp
<%@ page import="java.sql.*"%>
<%@ page import="java.io.*, java.util.*, java.lang.*"%>

<% ResultSet rs=null;
Connection con=null;
Statement stmt=null;
PreparedStatement psmt,psmt1;
Blob blobfile = null;
byte [] imgdata = null;
int status = 0;
boolean del_status = false;
OutputStream os = null;
try
{
String req_id=request.getParameter("id");
System.out.println("Entered"+req_id); Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); con=DriverManager.getConnection("Jdbc:Odbc:BTSJAVA","System","vijay"); stmt=con.createStatement();
psmt = con.prepareStatement("insert into img_temp values(?,?)");
int id_val = 1;
File img=new File("D:/photos/passport/PP.jpg");
FileInputStream fis= new FileInputStream(img);
psmt.setInt(2,id_val);
psmt.setBinaryStream(1,(InputStream)fis,(int)(img.length()));
status = psmt.executeUpdate();
//System.out.println("Trying to insert data");
if(status>0)
System.out.println("Success");
else
System.out.println("Unsuccess");

stmt.close();

stmt = con.createStatement();
rs = stmt.executeQuery("select imgfn from img_temp where id = 1"); //+Integer.parseInt(req_id));

response.setContentType("image/jpeg");
os = response.getOutputStream();

while(rs.next())
{
System.out.println("Getting Data");

os.write(rs.getBytes("imgfn"));

System.out.println("Got Data");
}

os.flush();
os.close();
}
catch(Exception e)
{
out.println(e);
e.printStackTrace();
}
%>

Create a html file with the following content

image tag src="img_uploadanddisplay.jsp?id=1"


Please send your feedback and queries to me.

2 comments:

AtRaM said...

Hi!

My problem is that I have the Blob images allocated in Oracle Database, so I have a list of people, it means that every person has its own image.
I don't know how to display every blob image in the table that I have in my jsp, could you help me?

Suresh Raju Pilli said...

What I have understand is, In your Database you have images. And you want to display in your JSP page?

In that case,
Relate the images to the employee or student table and try to retrieve blob images from the database and display in JSP.

Featured Post

Java Introdcution

Please send your review and feedback to psrdotcom@gmail.com