mydomain
No ADS
No ADS

Displaying Image from Database with Java Servlet

  1. Database
  2. Display Image from Database with Servlet

1. Database

** ORACLE **
create table PERSON
(
 ID              NUMBER(19) not null,
 NAME            VARCHAR2(50) not null,
 IMAGE_DATA      BLOB not null,
 IMAGE_FILE_NAME VARCHAR2(30) not null
) ;

alter table PERSON
 add constraint PERSON_PK primary key (ID);
** SQL SERVER **
create table PERSON
(
ID              NUMERIC(19,0) not null,
NAME            VARCHAR(50) not null,
IMAGE_DATA      IMAGE not null,
IMAGE_FILE_NAME VARCHAR(30) not null
) ;

alter table PERSON
add constraint PERSON_PK primary key (ID);
** MYSQL **
create table PERSON
(
ID              BIGINT not null,
NAME            VARCHAR(50) not null,
IMAGE_DATA      LONGBLOB not null,
IMAGE_FILE_NAME VARCHAR(30) not null
) ;

alter table PERSON
add constraint PERSON_PK primary key (ID);

2. Display Image from Database with Servlet

No ADS
In this post, I will guide you to display images from Database in Servlet. Normally, image data is stored in Database in a data column BLOB, you need to access to retrieve the data in byte[] and to write in response. In the section above, I have introduced a small database used for this lesson.
To display a Image you need a Servlet, and the URL might look like the following:
  • http://localhost:8080/ServletExamples/image?id=2
  • http://localhost:8080/ServletExamples/image?id=3
Make sure you have good knowledge of JDBC and Servlet. Otherwise you can visit:
JDBC:
Servlet:
Project:
Person.java
package org.o7planning.servletexamples.model;

public class Person {

    private Long id;
    private String name;
    private byte[] imageData;
    private String imageFileName;

    public Person() {

    }

    public Person(Long id, String name, String imageFileName, byte[] imageData) {
        this.id = id;
        this.name = name;
        this.imageData = imageData;
        this.imageFileName = imageFileName;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public byte[] getImageData() {
        return imageData;
    }

    public void setImageData(byte[] imageData) {
        this.imageData = imageData;
    }

    public String getImageFileName() {
        return imageFileName;
    }

    public void setImageFileName(String imageFileName) {
        this.imageFileName = imageFileName;
    }

}
DisplayImageServlet.java
package org.o7planning.servletexamples;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.o7planning.servletexamples.model.Person;
import org.o7planning.tutorial.jdbc.ConnectionUtils;

// /image?id=123
@WebServlet(urlPatterns = { "/image" })
public class DisplayImageServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;

  public DisplayImageServlet() {
      super();
  }

  private Person getImageInTable(Connection conn, Long id) throws SQLException {
      String sql = "Select p.Id,p.Name,p.Image_Data,p.Image_File_Name "//
              + " from Person p where p.id = ?";
      PreparedStatement pstm = conn.prepareStatement(sql);
      pstm.setLong(1, id);
      ResultSet rs = pstm.executeQuery();
      if (rs.next()) {
          String name = rs.getString("Name");
          byte[] imageData = rs.getBytes("Image_Data");
          String imageFileName = rs.getString("Image_File_Name");
          return new Person(id, name, imageFileName, imageData);
      }
      return null;
  }

  @Override
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      Connection conn = null;
      try {
          // Get Database Connection.
         // (See more in JDBC Tutorial)
          conn = ConnectionUtils.getMyConnection();
          Long id = null;
          try {
              id = Long.parseLong(request.getParameter("id"));
          } catch (Exception e) {

          }
          Person person = getImageInTable(conn, id);

          if (person == null) {
              // No record found, redirect to default image.
              response.sendRedirect(request.getContextPath() + "/images/noimage.jpg");
              return;
          }
       
          // trump.jpg, putin.png
          String imageFileName = person.getImageFileName();
          System.out.println("File Name: "+ imageFileName);
       
          // image/jpg
          // image/png
          String contentType = this.getServletContext().getMimeType(imageFileName);
          System.out.println("Content Type: "+ contentType);
       
          response.setHeader("Content-Type", contentType);
       
          response.setHeader("Content-Length", String.valueOf(person.getImageData().length));
       
          response.setHeader("Content-Disposition", "inline; filename=\"" + person.getImageFileName() + "\"");

          // Write image data to Response.
          response.getOutputStream().write(person.getImageData());

      } catch (Exception e) {
          throw new ServletException(e);
      }
  }

  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
      doGet(request, response);
  }

}
Running apps:
No ADS
No ADS