Friday, August 20, 2010

Download images from Database in JSP

Step:1 To create a "imageupload" table in Database

CREATE TABLE `imageupload` (
`id` bigint(20) NOT NULL auto_increment,
`imagefile` blob NOT NULL,
PRIMARY KEY (`id`)
)

Step:2 To create a web page "image.jsp"
<%@ page import="java.sql.*,java.io.*,java.util.*" %>
<%

String connectionURL = "jdbc:mysql://localhost:3306/userdetails";
if(request.getParameter("imgid")!=null && request.getParameter("imgid")!="")
{
int id = Integer.parseInt(request.getParameter("imgid"));

String filename = "image"+id+".jpg";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement st1=con.createStatement();
String strQuery = "select imagefile from imageupload where id="+id;

ResultSet rs1 = st1.executeQuery(strQuery);

String imgLen="";
if(rs1.next()){
imgLen = rs1.getString(1);
}
rs1 = st1.executeQuery(strQuery);
if(rs1.next()){
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = rs1.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
st1.close();
response.reset();
response.setContentType("image/jpg");
response.setHeader("Content-disposition","attachment; filename=" +filename);
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
}
}
catch (Exception e){
e.printStackTrace();
}
}
%>

Step:3 To create a "imageDownload.jsp"

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


Download Images






"center" border=0 width="200px">




<%

String connectionURL = "jdbc:mysql://localhost:3306/userdetails";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement stmt=con.createStatement();
String strQuery = "select id from imageupload";
ResultSet rs = stmt.executeQuery(strQuery);
int sno=0;
while(rs.next())
{
sno++;
%>
"background-color:#efefef;">



<%
}
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
%>
2 align="center">Download Images
2>
<%=sno%> "center">
"image.jsp?imgid=<%=rs.getInt(1)%>">
"image.jsp?imgid=<%=rs.getInt(1)%>" width="50" height="50">



No comments:

Post a Comment