inserting image in mysql database using browse button in servlets

Ads
 

inserting image in mysql database using browse button in servlets

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.

View Answers

November 13, 2010 at 2:54 PM

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">&nbsp;</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">&nbsp;</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();
}

November 13, 2010 at 2:58 PM

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>&nbsp;</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:

DownloadFileServlet DownloadFileServlet

<servlet-mapping>
    <servlet-name>DownloadFileServlet</servlet-name>
    <url-pattern>/DownloadFileServlet</url-pattern>
</servlet-mapping>

UploadServlet UploadServlet UploadServlet /UploadServlet

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


November 13, 2010 at 2:58 PM

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>&nbsp;</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:

DownloadFileServlet DownloadFileServlet

<servlet-mapping>
    <servlet-name>DownloadFileServlet</servlet-name>
    <url-pattern>/DownloadFileServlet</url-pattern>
</servlet-mapping>

UploadServlet UploadServlet UploadServlet /UploadServlet

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

Ads









Related Tutorials/Questions & Answers:
Export data in excel sheet via Browse and upload button into mysql database
Export data in excel sheet via Browse and upload button into mysql database  how to create a Browse & Upload Buttons and then save the information from it in mysql database's Table Am using struts2,hibernate for making
inserting image into database
inserting image into database  how to insert image into database using struts frame work and spring JDBC
Advertisements
Image upload in mysql database using jsp servlet
Image upload in mysql database using jsp servlet  Hello, I need code to insert image in mysql database, I have seen the code which is already in your portal but it is not inserting image into database it save in the folder
insert name city and upload image in database using mysql and jsp
insert name city and upload image in database using mysql and jsp   insert name city and upload image in database using mysql and jsp
how to store image in folder and stored image path in mysql database using JSP
how to store image in folder and stored image path in mysql database using JSP  how to store image in folder and stored image path in mysql database using JSP
retrive the employee details with image from mysql database using jsp servlet
retrive the employee details with image from mysql database using jsp servlet  im doing the web project to retrive the employee profile which i stored in the database using jsp servlet then want to show the result in the next jsp
Insert  Image into Database Using Servlet
of inserting image into database table using Servlet. This type of program is useful... Insert  Image into Database Using Servlet   ... to retrieve the image from database using Servlet. After retrieving the image from
How To Store Multilple Images In MySQL database dynamically with image uploader and then retrieve them in image gallery using java
How To Store Multilple Images In MySQL database dynamically with image uploader and then retrieve them in image gallery using java  How To Store Multilple Images In MySQL database dynamically with image uploader
insert name city image in database using mysql and jsp
insert name city image in database using mysql and jsp  how to insert name ,city and image in database in mysql and jsp   Here is an example in jsp that insert name, city and image to database. <%@ page import
Data is not inserting correctly in mysql database.
Data is not inserting correctly in mysql database.  Hello Sir, below is my code to insert data into database by list iteration...( "jdbc:mysql://localhost:3306/asteriskcdrdb", "root", "techsoft
browse image
browse image  how to browse the image in image box by browse button and save image in database by save button by swing   import java.sql.... java.awt.image.*; import java.awt.event.*; public class UploadImage extends JFrame { Image
browse image
browse image  how to browse the image in image box by browse button and save image in database by save button by swing   import java.sql.... java.awt.image.*; import java.awt.event.*; public class UploadImage extends JFrame { Image
how to upload an image from a jsp page to a mysql database table using jsp
how to upload an image from a jsp page to a mysql database table using jsp  how to upload an image from a jsp page to a mysql database table using jspstrong text
how to retrieve image from mysql database using java and show it in HTML img tag ?
how to retrieve image from mysql database using java and show it in HTML img tag ?  how to retrieve image from mysql database using java and show it in HTML img tag
How to insert and retreive an image in mysql database using spring mvc framework???
How to insert and retreive an image in mysql database using spring mvc framework???  I ve solved this problem based on the Product Search Application. Those who need this concept and code segment kindly copy it. Thanks and All
Submit button to MySQL database?
Submit button to MySQL database?  Need help linking html code to mysql database <html> <head> <meta http-equiv="Content-Type...").newInstance(); Connection connection = DriverManager.getConnection("jdbc:mysql
Submit button to MySQL database?
Submit button to MySQL database?  Need help linking html code to mysql database <html> <head> <meta http-equiv="Content-Type...").newInstance(); Connection connection = DriverManager.getConnection("jdbc:mysql
inserting multiple file formats into database using html
inserting multiple file formats into database using html   hi the code was working fine,i want to choose the file and then upload to database,by using html.whether it is possible to upload larger file size,please explain
Exception while inserting image in oracle using java
Exception while inserting image in oracle using java  import java.sql.*; import java.io.*; class Oracle2 { public static void main(String args...()); System.out.println("Image length: "+f.length()); System.out.println("No.of rows
How to use next and previous button(or href) for database table that is retrieved from MySQL DB using jsp,jstl,javascript
How to use next and previous button(or href) for database table that is retrieved from MySQL DB using jsp,jstl,javascript  when click on the next button/link then it must display next 10 record from database and same for previous
How To Store Image Into MySQL Using Java
How To Store Image Into MySQL Using Java In this section we will discuss about how to store an image into the database using Java and MySQL. This example... using Java. We will use the MySQL database system to store the image
How to browse excel file and stored the contents into the database using jsp/servlet?
How to browse excel file and stored the contents into the database using jsp/servlet?  Hi.. I want to browse excel file and stored the file data into the My-sql database using jsp/servlet
Browse an image
Browse an image  hi................ i want to browse an image from... this????? i am using java swing.........   import java.sql.*; import... java.awt.event.*; public class UploadImage extends JFrame { Image img; JTextField
inserting into mysql database with uid to be primary key and autoincrement
inserting into mysql database with uid to be primary key and autoincrement  hello, i am new to jsp and facing problem in creating a database entry...; Here is the code of inserting values from jsp form to database
Using MYSQL Database with JSP & Servlets.
what is the mysql in the database using php
what is the mysql in the database using php  what is the mysql in the database using php  Please visit the following link: PHP Database
what is the mysql in the database using php
what is the mysql in the database using php  what is the mysql in the database using php  Please visit the following link: PHP Database
How to retrieve image from mysql database in JSP?
How to retrieve image from mysql database in JSP?  Hi, I need JSP same codes for learning to get image which is stored in MySQL Database. How to retrieve image from mysql database in JSP? Thanks   Hi, You can write
database connectivity using mysql
database connectivity using mysql  java file: eg1.java package eg... seconds) I am using Netbeans 5.5, mysql server 5.0, to get data from table...[]) throws SQLException { try { String connectionURL = "jdbc:mysql
Image name,image path into database and image into folder using jsp
Image name,image path into database and image into folder using jsp  How to insert image path and image name into oracle database and image into folder using jsp
how to fetch image from mysql using jsp
how to fetch image from mysql using jsp  how to fetch image from mysql using jsp

Ads