Latest Tutorials| Questions and Answers|Ask Questions?|Site Map



Home Answers Viewqa JSP-Servlet inserting image in mysql database using browse button in servlets
Login         

View Questions and Answers by Category

Advertisements


 
Have Programming Question? Ask it here!
 
 
 


Praveena Naregudem
inserting image in mysql database using browse button in servlets
3 Answer(s)      4 years and 2 months ago
Posted in : JSP-Servlet


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.


Advertisement
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
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
Using MYSQL Database with JSP & Servlets.
Using MYSQL Database with JSP & Servlets.  ... acceres the MYSQL database. Here I am using MYSQL & tomcat server... current command   quit (\q)  Quit mysql  
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
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
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
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
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
Inserting Image in Database Table
Inserting Image in Database Table   ... 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. Lets' take
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
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
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
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
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 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 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
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
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
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 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 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
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
 

 

 

DMCA.com