Amazon Great Offers

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.
Post a Comment

Featured Post

Java Introdcution

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