how to display an image from mysql database on a jsp page?

31,791

why dont you try like this:

  1. i have a getImageDetails.jsp to retrive the image data from the database based on user_id or name or some other constraint as follows (put the code in jsp/servlet page)

    int img_id = Integer.parseInt(request.getParameter("your_id"));
    Connection con = //get your connection object here ;
    ResultSet rs = null;
    PreparedStatement pstmt = null;
    OutputStream oImage;
    try {
    pstmt = con.prepareStatement("your sql statement for retriving the image column data");
    pstmt.setInt(1, img_id);
    rs = pstmt.executeQuery();
        if(rs.next()) {
            byte barray[] = rs.getBytes(1);
            response.setContentType("image/gif");
            oImage=response.getOutputStream();
            oImage.write(barray);
            oImage.flush();
            oImage.close();
        }
    }
    catch(Exception ex){
        //ex.printStackTrace();
    }finally {
        try{
        if(con!=null)
           con.close();
        }catch(Exception ex){
           // ex.printStackTrace();
        }
    }
    
  2. then i am calling this page from html or any another jsp page as follows

    < img src="getImageDetails.jsp?your_id=12" width="50" height="50" />

please try like this you will get answer

let me know the status happy coding

Share:
31,791
JavaCoding
Author by

JavaCoding

Updated on July 09, 2022

Comments

  • JavaCoding
    JavaCoding almost 2 years

    I want to display an image that is stored in a MySQL database. To retrieve the image, I am using a servlet. Please tell me how to display it in a jsp page. This is the flow:

    login.html ---> dologin.jsp
    

    login.html and the servlet are nearly ready. Please tell me how to finish dologin.jsp.

    login.html

    <html>
    <head>
    <style type="text/css">
    html, body, div, h1, h2, h3, h4, h5, h6, p, img, dl,
      dt, dd, ol, ul, li, table, tr, td, form, object, embed,
      article, aside, command, details, fieldset,
      figcaption, figure, footer, group, header, hgroup, legend
    {
      margin: 0;
      padding: 0;
      border: 0;
    }
    html {
      font: 82.5% verdana, helvetica, sans-serif;
      background: #fff;
      color: #333;
      line-height: 1;
      direction: ltr;
    }
    html, body {
      position: absolute;
      height: 100%;
      min-width: 100%;
    }   
    
    table {
      border-collapse: collapse;
      border-spacing: 0;
    }
    
    
    .signin-header {
      padding: 10px 12px 5px;
      background:#00AAFF;
      border: 1px solid #e5e5e5;
      width: 362px;
      float: right;
    }
    .signin-box {
      padding: 20px 25px 15px;
      background:#DEDEDE;
      border: 1px solid #e5e5e5;
      width: 335px;
      float: right;
    }
    
    .button {
      min-width: 46px;
      text-align: center;
      color: #444;
      font-size: 11px;
      font-weight: bold;
      height: 27px;
      padding: 0 8px;
      line-height: 27px;
      border-radius: 2px;
      transition: all 0.218s;
      border: 1px solid #dcdcdc;
      background-color: #f5f5f5;
      cursor: default;
    }
    
    *+html .button {
      min-width: 70px;
    }
    
    button.button,
    input[type=submit].button {
      height: f1f1f1px;
      line-height: 29px;
      vertical-align: bottom;
      margin: 0;
    }
    
    .button:hover {
      border: 1px solid #c6c6c6;
      color: #333;
      text-decoration: none;
      transition: all 0.0s;
      background-color: #f8f8f8;
      box-shadow: 0 1px 1px rgba(0,0,0,0.1);
    }
    .button:active {
      background-color: #f6f6f6;
      box-shadow: inset 0 1px 2px rgba(0,0,0,0.1);
    }
    .button:visited {
      color: #666;
    }  
    .button-submit {
      border: 1px solid #3079ed;
      color: #fff;
      text-shadow: 0 1px rgba(0,0,0,0.1);
      background-color: #4d90fe;
    }
    .button-submit:hover {
      border: 1px solid #2f5bb7;
      color: #fff;
      text-shadow: 0 1px rgba(0,0,0,0.3);
      background-color: #357ae8;
    }
    button-submit:active {
      background-color: #357ae8;
      box-shadow: inset 0 1px 2px rgba(0,0,0,0.3);
    }
    
    .footer-bar {
      position: absolute;
      bottom: 0;
      height: 35px;
      width: 100%;
      border-top: 1px solid #ebebeb;
      overflow: hidden;
    }
    .footer {
      padding-top: 9px;
      font-size: .85em;
      white-space: nowrap;
      line-height: 0;
    }
    .footer ul {
      color: #999;
      float: left;
      max-width: 80%;
    }
    .footer ul li {
      display: inline;
      padding: 0 1.5em 0 0;
    }
    .footer a {
      color: #333;
    }
    .footer .lang-chooser-wrap {
      float: right;
      max-width: 20%;
    }
    .footer .lang-chooser-wrap img {
      vertical-align: middle;
    }
    .footer .attribution {
      float: right;
    }
    .footer .attribution span {
      vertical-align: text-top;
    }
    .content {
      padding: 0 44px;
    }
    
    .table {
      padding: 0 55px
    }
    </style>
    <script type="text/javascript">
    function ccheck()
    {
    uid=document.f1.uid.value;
    cpass=document.f1.cpass.value;
    
    if(uid=="" || uid==null)
    {
    alert("Plz. Enter Your User ID");
    document.f1.uid.focus();
    return false;
    }
    if(cpass=="" || cpass==null)
    {
    alert("Plz. Enter Your Password");
    document.f1.cpass.focus();
    return false;
    }
    return true;
    }
    </script>
    <title>Login Page</title>
    </head>
    <body onload="document.f1.uid.focus()" style="background-image:url('medical.jpg');background-position: center">
        <form id="f1" name="f1" action="doDelete.jsp" method="get" onsubmit="return ccheck()">
    
            <img src="header.png"><br><br><br><br><br>
            <table><tr><td>
                <table class="table"><tr><td>
                    <table class="table"><tr><td>
                        <div class="content"><div class="signin-header"><h3>Welcome to DiaEmr</h3></div></div>
                    </td></tr>
                    <tr><td>
                        <div class="content">
                        <div class="signin-box">
                        <p class="one">
                            Welcome to all at the <b>"Workshop on Ileal Interposition".</b><br>
    
                            <b>Brazil</b> to inaugurate & launch this very important Data Registry<br>
                            Key features of the solution-<br>
                        </div>  
                    </div>
                </td></tr></table>
            </td>
            <td>image</td>
            <td>
                <table class="table"><tr><td>
                    <div class="content">
                        <div class="signin-header">
                            <h3>Portal Login</h3>
                        </div>
                    </div>
                </td></tr>
                <tr><td>
                    <div class="content">
                        <div align="center" class="signin-box">
                            <table class="table"><tr><td>
                                <b>User ID</b></td>
                            <td><input name="uid" type="text" /></td>
                            </tr>
                            <tr><td>
                                <b>Password</b></td>
                            <td><input name="cpass" type="password" /></td>
                            </tr>
                            <tr>
                                <td><input type="submit" class="button button-submit" value="Submit" /></td>
                                <td><input type="reset" class="button button-submit" value="Reset" /></td>
                            <tr>New User<a href ="UserRegistration.jsp">Register</a></tr><br>
                            </tr></table>
                        </div>
                    </div>
                </td></tr></table>
            </td></tr></table>
        </td></tr></table>
        <div class="footer-bar">
            <img align="left" src="footer.png">
        </div>
    </form>
    </body>
    </html>
    

    servlet

    import java.sql.*;
    import DB.DataBaseConnection;
    
    import java.io.IOException;
    import java.io.InputStream;
    
    import javax.servlet.ServletException;
    import javax.servlet.ServletOutputStream;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class imagetestServlet
     */
    @WebServlet("/imagetestServlet")
    public class imagetestServlet extends HttpServlet {
    
        private static final long serialVersionUID = 1L;
    
        /**
         * @see HttpServlet#HttpServlet()
         */
        public imagetestServlet() {
            super();
            // TODO Auto-generated constructor stub
        }
    
        /**
         * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
         */
        public void doGet(HttpServletRequest request, HttpServletResponse response) 
                  throws IOException,ServletException {
    
                     Blob image = null;
                      Connection con = null;
                      Statement stmt = null;
                      ResultSet rs = null;
                      DataBaseConnection db= new DataBaseConnection();
                      ServletOutputStream out = response.getOutputStream();
                      try {
                      Class.forName("com.mysql.jdbc.Driver");
                      con=db.connet();
                      stmt = con.createStatement();
                      rs = stmt.executeQuery("select img from one where  id = '4'");
                      if (rs.next()) {
                      image = rs.getBlob(1);
                      } else {
                      response.setContentType("text/html");
    
                      out.println("<font color='red'>image not found for given id</font>");
    
                      return;
                      }
                      response.setContentType("image/gif");
                 InputStream in = image.getBinaryStream();
                  int length = (int) image.length();
                  int bufferSize = 1024;
                  byte[] buffer = new byte[bufferSize];
                  while ((length = in.read(buffer)) != -1) {
                  out.write(buffer, 0, length);
                  }
                  in.close();
                  out.flush();
    
                } catch (Exception e) {
                  response.setContentType("text/html");
                  out.println("<html><head><title>Unable To Display image</title></head>");
                  out.println("<body><h4><font color='red'>Image Display Error=" + e.getMessage() +
                   "</font></h4></body></html>");
                  return;
                  } 
        }
    
        /**
         * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
         */
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            // TODO Auto-generated method stub
        }
    
    }
    
  • JavaCoding
    JavaCoding about 11 years
    its throwing java.nullpointer exception. well i am checking it
  • radha krishna
    radha krishna about 11 years
    can you post total error msg to me so that i will let you know where is the problem and one more thing have you updated the code with your database details check it once
  • JavaCoding
    JavaCoding about 11 years
    your < img src="getImageDetails.jsp?your_id=12" width="50" height="50" /> helped me because i have developed using servlet.thanks
  • radha krishna
    radha krishna about 11 years
    thats not a big issue whether it is jsp or servlet. you may copy the code to servlet. i think you know this concept right. try to change that to servlet. let me know if you get any problem
  • JavaCoding
    JavaCoding about 11 years
    i have a form having fields like name,age etc and one field to get image. i have 2 tables one for storing details and another for storing image. the form action calls a servlet that stores details except image. i have designeda servlet that stores images into the DB. Please tell me how to call this servlet. Can one submit call 2 servlets.