image를 DB에서 웹으로

 

이미지 저장

 테이블 생성
create table test(
img blob
);


import sun.misc.*;
import java.sql.*;
import java.io.*;

public class test
{
public static void main(String args[])
{
try {

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@127.0.0.1:1521:orcl", "xxx", "xxx");
con.setAutoCommit(false);

File file = new File("Sample.jpg"); 
FileInputStream fis = new FileInputStream(file); 

PreparedStatement ps = con.prepareStatement("insert into test (img) values (?)"); 
ps.setBinaryStream(1, fis, (int)file.length()); 
ps.executeUpdate(); 

ps.close(); 
con.close();
fis.close(); 

} catch(Exception e) {
System.out.println(e.toString());
}

}

 

DB에서 이미지 읽어서 웹으로 보여주기 JSP

<%@ page import="java.sql.*, java.io.*"%><%
  String driver = "com.sybase.jdbc3.jdbc.SybDriver";
  String strUrl = "jdbc:sybase:Tds:11.22.1.111:1111/Dbname";  
       //                   jdbc db           local      port  sid.
    Connection conn   = null;      
    Statement  stmt   = null;
    PreparedStatement pstmt = null;
    ResultSet rs;            
    ByteArrayOutputStream os = null;
    byte[] result = null;
   
       try{
            Class.forName(driver);
        }catch(Exception exception)        {
            System.out.println(exception);
        }

        try{
         Properties p=new Properties();
       p.put("user","ebaiusr");   
       p.put("password","ebaiusrdb");              
          conn = DriverManager.getConnection(strUrl,p);

          // 디비에서 읽는다.
          pstmt = conn.prepareStatement("select PIC_FILE from PIC_FILE where RCN = '780728' "); 
          rs = pstmt.executeQuery();
          if(rs.next()) {
            InputStream is = rs.getBinaryStream(1);
            os = new ByteArrayOutputStream();            
            int i;
            while((i = is.read()) != -1) {
                os.write(i);         
            }
            result = os.toByteArray();
            is.close();
            os.close();
            }
        } catch(Exception e) {
            out.println("error sql execute");
            out.println("result = " + e.toString());
        }
        finally
        {
            try {
                if(conn != null) conn.close();
            }
            catch(Exception e) {
                out.println("error conn close");
            }
        }
response.setContentType("image/jpeg");
ServletOutputStream oout = response.getOutputStream();
oout.write(result);
oout.flush();
oout.close();
%>