Tuesday, 3 May 2011

Retrieve image from the database:

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>

<%


ResultSet rs = null;

PreparedStatement psmnt = null;
Connection conn=null;

InputStream sImage;
try {

Class.forName("com.mysql.jdbc.Driver");

conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/op?user=root&password=enggheads");

psmnt = conn.prepareStatement("SELECT fname FROM test WHERE id = ?");
psmnt.setString(1, "1");

rs = psmnt.executeQuery();

String imgLen="";
if(rs.next()){

imgLen = rs.getString(1);
System.out.println(imgLen.length());
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
out.println("index"+index);

response.reset();
response.setContentType("image/png");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}

catch(Exception ex){
out.println("error :"+ex);
}
finally {
// close all the connections
rs.close();
psmnt.close();
conn.close();
}
%>

No comments:

Post a Comment