Hi,I want to insert a image in mysql database using browse button. and, i want to display all inserted images in a form from there i want to download the image. could you plz help me.
Hi Friend,
We have created an application. Follow these steps.
1)page.jsp:
<HTML> <HEAD><TITLE>Display file upload form to the user</TITLE></HEAD> <BODY> <FORM ENCTYPE="multipart/form-data" ACTION="../UploadServlet" METHOD=POST> <br><br><br> <center> <table border="0" bgcolor=#ccFDDEE> <tr><center><td colspan="2" align="center"><B>UPLOAD THE FILE</B><center></td></tr> <tr><td colspan="2" align="center"> </td></tr> <tr><td><b>Choose the file To Upload:</b></td><td><INPUT NAME="file" TYPE="file"></td></tr> <tr><td colspan="2" align="center"> </td></tr> <tr><td colspan="2" align="center"><input type="submit" value="Send File"> </td></tr> <table> </center> </FORM> </BODY> </HTML>
2)UploadServlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class UploadServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String saveFile="";
String contentType = request.getContentType();
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File(saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
out.println("You have successfully upload the file by the name of: "+saveFile);
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
File f = new File(saveFile);
PreparedStatement psmnt = connection.prepareStatement("insert into image(image) values(?)");
FileInputStream fis = new FileInputStream(f);
psmnt.setBinaryStream(1, (InputStream)fis, (int)(f.length()));
int s = psmnt.executeUpdate();
if(s>0) {
System.out.println("Uploaded successfully !");
}
else{
System.out.println("unsucessfull to upload file.");
}
}
catch(Exception e){e.printStackTrace();
}
continue..
out.println("<table align='center' border=1 width='200px'>");
out.println("<tr><td colspan=2 align='center'><b>Download Images</b></td></tr><tr><td colspan=2> </td></tr>");
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement stmt=con.createStatement();
String strQuery = "select image_id from image";
ResultSet rs = stmt.executeQuery(strQuery);
int sno=0;
while(rs.next())
{
sno++;
out.println("<tr style=background-color:#efefef><td><b>"+sno+"</b></td><td align='center'><a href=DownloadFileServlet?id="+rs.getInt(1)+"><img src=DownloadFileServlet?id="+rs.getInt(1)+" width=50 height=50></a></td></tr>");
}
out.println("</table>");
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
}
}
}
3)DownloadFileServlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
String filename = "image"+id+".jpg";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st1=con.createStatement();
String strQuery = "select image from image where image_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();
}
}
}
4)Do servlet mapping in web.xml:
<servlet-mapping>
<servlet-name>DownloadFileServlet</servlet-name>
<url-pattern>/DownloadFileServlet</url-pattern>
</servlet-mapping>
For the above code, we have created a table named 'image' into database.
CREATE TABLE `image` (
`image_id` bigint(40) NOT NULL auto_increment,
`image` longblob,
PRIMARY KEY (`image_id`)
)
Thanks
continue..
out.println("<table align='center' border=1 width='200px'>");
out.println("<tr><td colspan=2 align='center'><b>Download Images</b></td></tr><tr><td colspan=2> </td></tr>");
String connectionURL = "jdbc:mysql://localhost:3306/test";
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection(connectionURL,"root","root");
Statement stmt=con.createStatement();
String strQuery = "select image_id from image";
ResultSet rs = stmt.executeQuery(strQuery);
int sno=0;
while(rs.next())
{
sno++;
out.println("<tr style=background-color:#efefef><td><b>"+sno+"</b></td><td align='center'><a href=DownloadFileServlet?id="+rs.getInt(1)+"><img src=DownloadFileServlet?id="+rs.getInt(1)+" width=50 height=50></a></td></tr>");
}
out.println("</table>");
rs.close();
con.close();
stmt.close();
}
catch(Exception e)
{
e.getMessage();
}
}
}
}
3)DownloadFileServlet.java:
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DownloadFileServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException{
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
String filename = "image"+id+".jpg";
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
Statement st1=con.createStatement();
String strQuery = "select image from image where image_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();
}
}
}
4)Do servlet mapping in web.xml:
<servlet-mapping>
<servlet-name>DownloadFileServlet</servlet-name>
<url-pattern>/DownloadFileServlet</url-pattern>
</servlet-mapping>
For the above code, we have created a table named 'image' into database.
CREATE TABLE `image` (
`image_id` bigint(40) NOT NULL auto_increment,
`image` longblob,
PRIMARY KEY (`image_id`)
)
Thanks