inserting image in mysql database using browse button in servlets

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









Related Tutorials/Questions & Answers:
inserting image in mysql database using browse button in servlets
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
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
Advertisements
Using a image for Browse button instead of normal html Browse button for Uploading files from a JSP - JSP-Servlet
Using a image for Browse button instead of normal html Browse button for Uploading files from a JSP  I am using the following code snippet.... Is it not possible to use a image instead of normal html Browse button for uploading files
inserting image into database
inserting image into database  how to insert image into database using struts frame work and spring JDBC
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
Using MYSQL Database with JSP & Servlets.
Using MYSQL Database with JSP & Servlets.  ... acceres the MYSQL database. Here I am using MYSQL & tomcat server...   exit (\q)  Exit mysql. Same as quit
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
inserting an path of an image in database - JDBC
inserting an path of an image in database  hello kindly help related... an image using web cam.... and when the image is saved in a project at the same time its full path should be inserted in the database(MS Sql 2000).. I m able
Insert Image into Database Using Servlet
Insert  Image into Database Using Servlet   ... image into database table using Servlet. This type of program is useful in social... the image from database using Servlet. After retrieving the image from database
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 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 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
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 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
Inserting Image in Database Table
Inserting Image in Database Table   ... This program helps the user to insert an image in the MySQL database table. To insert an image, you need to establish a connection with MySQL database
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
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
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
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
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
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
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
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... you about how to store image into database using Java. We will use the MySQL
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
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
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
Using MYSQL Database with JSP & Servlets.
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
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
Inserting Image in a database Table
Inserting Image in MySql Database Table... understand the concept of inserting a image in the database table, so go through... database which we are using.  After the connection establishment we will pass
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
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
Problem in uploading image to to mysql database
Problem in uploading image to to mysql database  Hi, need some help... a user click the submit button the name, city and the image(Save as BLOB) must be save in the database. and the image will also save in the desired folder. i
Problem in uploading image to to mysql database
Problem in uploading image to to mysql database  Hi, need some help... a user click the submit button the name, city and the image(Save as BLOB) must be save in the database. and the image will also save in the desired folder. i
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... Image Enter your name... into database"); } catch(Exception e) { System.out.println(e); } %> when i
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... Image Enter your name... into database"); } catch(Exception e) { System.out.println(e); } %> when i
how to read data from excel file through browse and insert into oracle database using jsp or oracle???
how to read data from excel file through browse and insert into oracle database... a browse button which can upload a excelfile and after uploading the data should..., in these examples MySQL is used as database system if you want to use the Oracle
Save profile and image to mysql database, and view the image in another jsp page
Save profile and image to mysql database, and view the image in another jsp page  Pls. need help in saving the profile info with the image in mysql database.. some basic code pls in jsp... thanks in advance
how to fetch image from mysql using jsp
how to fetch image from mysql using jsp  how to fetch image from mysql using jsp
i am inserting an image into database but it is showing relative path not absolute path
i am inserting an image into database but it is showing relative path not absolute path   hi my first page......... <html> <head>..."); out.println("ur values are inserted into database"); } catch(Exception e
image store in database - JDBC
; Inserting Image in Database Table http://www.roseindia.net/jdbc/jdbc-mysql/insert... to store image into database. Check at http://www.roseindia.net/servlets/insert...image store in database  Dear Deepak Sir, If I want to store image
How to set attachment from browse button to send mails using java mail api
How to set attachment from browse button to send mails using java mail api   Hello Sir, I am making Email Sending app using java mail api... browse button but attachment is not loading properly using browse button because
Saving image and text in mysql db using spring?
Saving image and text in mysql db using spring?  Hii, My requirement is to save the employee details(including image) into mysql db.i want to save the image location in db .And actual image(binary formate) should save
inserting multiple file formats into database
inserting multiple file formats into database  hi i want to insert multiple file format like .pdf.doc.zip into mysql database using jsp
BROWSE BUTTON CODE
BROWSE BUTTON CODE  HOW TO STORE THE FILE BROWSE TO THE DATABASE   JSP File Upload 1)page.jsp: <%@ page language="java" %> <... connectionURL = "jdbc:mysql://localhost:3306/test";; ResultSet rs = null

Ads