
How to access image file from database using jsp?

retrieveimage.jsp:
<%@page import="java.sql.*,java.io.*"%>
<%
try{
InputStream sImage;
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("SELECT images FROM image WHERE id = 1");
if(rs.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = rs.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1 ){
response.getOutputStream().write(bytearray,0,size);
}
}
con.close();
}
catch(Exception ex){
out.println("error :"+ex);
}
%>
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.