ramesh
how to store and then immediately retrieve when store the image into database?
2 Answer(s)      2 years and 8 months ago
Posted in : JSP-Servlet

how to store and then immediately retrieve when store the image into database?

Advertisement
View Answers

September 3, 2012 at 5:58 PM


Here is a jsp code that insert and retrieve image from MYSQL database.

<%@page import="java.sql.*,java.io.*"%>
<%
try{
    InputStream sImage;
Class.forName("com.mysql.jdbc.Driver");
           Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
File imgfile = new File("C:/flower3.jpg");
      FileInputStream fin = new FileInputStream(imgfile);
      PreparedStatement pre = con.prepareStatement("insert into image(images) values(?)");
      pre.setBinaryStream(1,fin,(int)imgfile.length());
      pre.executeUpdate();
      System.out.println("Inserting Successfully!");
      pre.close();
      Statement st=con.createStatement();
      ResultSet rs=st.executeQuery("select images from image");
if(rs.last()){
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);
}
}
rs.close();
st.close();
con.close();
}
catch(Exception ex){
out.println("error :"+ex);
}
%>


January 9, 2013 at 11:09 AM


Inserting is done. But its not showing the image.










Related Tutorials/Questions & Answers:
Advertisements