Upload Image and Store in BLOB Table


This topic I'm going to talk about how to store image in database and retrieve them for display.

Step 1. Create table

Code:
create table test_blob (
  blob_id varchar2(2),
  blob_file varchar2(50),
  blob_type varchar2(50),
  blob_content blob
);

Step 2 Create class to hold data

Code:
package app.image.demo;

import java.awt.Image;
import java.awt.Toolkit;

public class BlobRec {
 
  private String id;
  private String file;
  private String desc;
  private String type;
  private byte[] byteStream;
 
  public void setID (String id) {
    this.id = id;
  }
 
  public String getID () {
    return this.id;
  }
 
  public void setFile (String file) {
    this.file = file;
  }
 
  public String getFile () {
    return this.file;
  }
 
  public void setDesc (String desc) {
    this.desc = desc;
  }
 
  public String getDesc () {
    return this.desc;
  }
 
  public void setType (String type) {
    this.type = type;
  }
 
  public String getType () {
    return this.type;
  }
 
  public void setByteStream (byte[] byteStream) {
    this.byteStream = byteStream;
  }
 
  public byte[] getByteStream () {
    return this.byteStream;
  }
 
  public Image getImage () {
    Image image = Toolkit.getDefaultToolkit().createImage(getByteStream());
    return image;
  }
 
}

Step 3 Create class to process data

Code:
package app.image.demo;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import oracle.jdbc.OraclePreparedStatement;
import oracle.jdbc.OracleResultSet;
import oracle.sql.BLOB;

public class UploadBlob {
 
  private Connection connection = null;
  private ResultSet rs;
  private Statement stmt;
  private PreparedStatement pstmt;
 
  public UploadBlob() {
   
    try {
      //Load the JDBC driver
      String driverName = "oracle.jdbc.driver.OracleDriver";
      Class.forName(driverName);
     
      //Create a connection to the database
      String serverName = "localhost";
      String portNumber = "1521";
      String sid = "testdbs";
      String url = "jdbc:oracle:thin:@" + serverName + ":"
                                + portNumber + ":"
                                + sid;
     
      String username = "scott";
      String password = "tiger";
      connection = DriverManager.getConnection(url, username, password);
      //System.out.println("Application connect to DB successfully.");
          
    } catch (ClassNotFoundException e){
      // Could not find the database driver
      System.out.println("ClassNotFoundException: "+e.getMessage());
    } catch (SQLException e){
      // Could not connect to the database
      System.out.println("SQLException: "+e.getMessage());
    }
   
  }
 
  public void close() {
 
    try {
      if (rs != null) {
        rs.close();
        rs = null;
      }
      if (stmt != null) {
        stmt.close();
        stmt = null;
      }
      if (pstmt != null) {
        pstmt.close();
        pstmt = null;
      }
      if (!connection.isClosed()) {
        connection.close();
        connection = null;
      }
    } catch (SQLException e) {
      // nothing
    }
    //System.out.println("Disconnect from database.");
   
  }
 
  public void loadBlob(String bid, String files, String types, InputStream stream) {
 
    OraclePreparedStatement ops;
    String sql = "insert into test_blob values(?, ?, ?, ?)";
    try {
      BLOB blob = getBLOB(connection, stream);
     
      ops = (OraclePreparedStatement)connection.prepareStatement(sql);
      ops.setString(1, bid);
      ops.setString(2, files);
      ops.setString(3, types);
      ops.setBLOB(4, blob);
      ops.execute();
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
     
  }
 
  public BlobRec getBlobRec(String blob_id) {
    BlobRec br = new BlobRec();
    try {
      stmt = connection.createStatement();
      String sql = "select * from test_blob where blob_id = '" + blob_id + "'";
      rs = stmt.executeQuery(sql);
      if (rs.next()) {
        br.setID(rs.getString(1));
        br.setFile(rs.getString(2));
        br.setType(rs.getString(3));
        BLOB blob = ((OracleResultSet)rs).getBLOB (4);
        if (blob != null) {
          br.setByteStream(getByteArray(blob));
        }
      }
    } catch (SQLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    }
    return br;
  }
 
  public byte[] getByteArray (BLOB blob) throws SQLException, IOException {
 
    BufferedInputStream bis;
    ByteArrayOutputStream bo;
    bis = new BufferedInputStream(blob.getBinaryStream());
    bo = new ByteArrayOutputStream();
    int MAXBUFSIZE = 1024;
    byte[] buf = new byte[MAXBUFSIZE];
    int n = 0;
   
    while ((n = bis.read(buf, 0, MAXBUFSIZE)) != -1) {
      bo.write(buf, 0, n);
    }
   
    bo.flush();
    bo.close();
    bis.close();
    buf = null;
   
    return bo.toByteArray();
          
  }
 
  public BLOB getBLOB (Connection connection, InputStream inputStream)
  throws SQLException, IOException {
 
    BLOB blob;
    blob = BLOB.createTemporary(connection, false, BLOB.DURATION_SESSION);
    byte[] binaryBuffer;
    long position = 1;
    int bytesRead = 0;
    binaryBuffer = new byte[inputStream.available()];
   
    while ((bytesRead = inputStream.read(binaryBuffer)) != -1) {
      blob.putBytes(position, binaryBuffer);
      position += bytesRead;
    }
   
    return blob;
   
  }
 
}

Step 4 Create class to read image from file

Code:
package app.image.demo;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class LoadImage {
 
  public static void main (String arg[]) {
 
    try {
      UploadBlob upload = new UploadBlob();
      System.out.println("Connected...");
     
      String filename = "view.jpg";
      String bid = "1";
     
      // load the image from file
      InputStream inputStream = new FileInputStream(filename);
      // store in database
      upload.loadBlob(bid, filename, "jpeg", inputStream);
      upload.close();
     
      System.out.println("Finished...");
      inputStream.close();
    catch (IOException e) {
      e.printStackTrace();
    }
  }
 
}

Step 5 Create class to retrieve image and display

Code:

package app.image.demo;

import java.awt.GridLayout;
import java.awt.Image;
import java.io.IOException;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

public class ShowImage {
 
  public static Image getImage() {
 
    UploadBlob upload = new UploadBlob();
    BlobRec br = upload.getBlobRec("1");
    Image image = br.getImage();
    upload.close();
    return image;
   
  }
 
  public static void main(String[] args) throws IOException {
 
    JPanel p = new JPanel(new GridLayout(1,1,1,1));
    p.add(new JLabel(new ImageIcon(getImage())));
    JFrame f = new JFrame("Blob DB");
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    /*
    // for custom exit
    f.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e) {
         System.out.print("Do something before close");
            System.exit(0);
        }
    });
    */
    f.getContentPane().add(new JScrollPane(p));
    f.pack();
    f.setLocationRelativeTo(null);
    f.setVisible(true);
   
  }
 
}

Next topic I gonna talk about how to upload image in web application

Step 1 Create a servlet class

Code:

package app.image.demo;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
Require common file upload library: http://commons.apache.org/fileupload/
*/
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;

/**
Require PNG Encoder library: http://catcode.com/pngencoder/
*/
import com.keypoint.PngEncoder;

public class UploadServlet extends HttpServlet {
 
  private static final long serialVersionUID = 1L;
 
  public void doPost(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    ServletOutputStream sos = response.getOutputStream();
    BufferedImage bufferedImage;
   
    // Create a new file upload handler
    ServletFileUpload sfUpload = new ServletFileUpload();
   
    // Parse the request
    FileItemIterator iter;
    try {
      iter = sfUpload.getItemIterator(request);
      while (iter.hasNext()) {
        FileItemStream item = iter.next();
        String fieldName = item.getFieldName();
        String contentType = item.getContentType();
        InputStream inputStream = item.openStream();
        if (item.isFormField()) {
          //System.out.println("Field Value: " + Streams.asString(inputStream));
        } else {
          // Process the input stream
          String filePath = item.getName();
          //System.out.println("Field Value: " + filePath);
          String fileName = filePath.substring(filePath.lastIndexOf("\\")+1);
          //System.out.println("File Name: " + fileName);
         
          // Store data into database
          String id = "1";
          Upload upload = new Upload();
          upload.loadBlob(id, fileName, contentType, inputStream);
          BlobRec br = upload.getBlobRec(id);
         
          if (isImage(br.getType())) {
            Image image = br.getImage();
            bufferedImage = createBufferedImage(image);
           
            // Convert to the PNG format
            PngEncoder encoder = new PngEncoder(bufferedImage, false, 0, 9);
            // response.setContentType("image/png");
            // Stream out the image
            sos.write(encoder.pngEncode());
          }
          upload.close();
        }
      }
    } catch (FileUploadException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    sos.flush();
    sos.close();
  }
 
  public void doGet(HttpServletRequest request, HttpServletResponse response)
  throws ServletException, IOException
  {
    doPost(request, response);
  }
 
  private boolean isImage(String contentType) {
    // not count the icon image or "image/x-ico"
    return contentType.equals("image/gif") ||
           contentType.equals("image/pjpeg") ||
           contentType.equals("image/x-png");
  }
 
  private BufferedImage createBufferedImage(Image image) {
    int width = image.getWidth(null);
    int height = image.getHeight(null);
    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    Graphics2D g2d = bi.createGraphics();
    g2d.drawImage(image, 0, 0, null);
    return bi;
  } 
}

Step 2 Create web.xml file

Code:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app
    PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
    "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">

<web-app>
  <servlet>
    <servlet-name>UploadServlet</servlet-name>
    <servlet-class>app.image.demo.UploadServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>UploadServlet</servlet-name>
    <url-pattern>/UploadServlet</url-pattern>
  </servlet-mapping>

  <!-- Establish the default MIME type mappings -->
  <mime-mapping>
    <extension>png</extension>
    <mime-type>image/png</mime-type>
  </mime-mapping>

</web-app>

Step 3 Create test.html file

Code:

<HTML>
<HEAD>
<TITLE>Test Upload</TITLE>
</HEAD>
<BODY>

<FORM ACTION="UploadServlet"  ENCTYPE="multipart/form-data" METHOD=POST>
File: <INPUT TYPE="file" NAME="FileName" SIZE="30"><BR>
<INPUT TYPE="submit">
</FORM>

</BODY>
</HTML>

Lastly build togather a war file

 

คำสำคัญ (Tags): #insert image to blob table#java programming
หมายเลขบันทึก: 176280เขียนเมื่อ 10 เมษายน 2008 15:56 น. ()แก้ไขเมื่อ 11 มิถุนายน 2012 13:48 น. ()สัญญาอนุญาต: ไม่สงวนสิทธิ์ใดๆจำนวนที่อ่านจำนวนที่อ่าน:


ความเห็น (1)

เป็นประโยชน์อย่างมากครับ ขอบคุณครับ

พบปัญหาการใช้งานกรุณาแจ้ง LINE ID @gotoknow
ClassStart
ระบบจัดการการเรียนการสอนผ่านอินเทอร์เน็ต
ทั้งเว็บทั้งแอปใช้งานฟรี
ClassStart Books
โครงการหนังสือจากคลาสสตาร์ท