前提:使用JSP顯示圖片。圖片的儲存位置在資料庫中。
  方法:用JDBC串連資料庫,從資料庫讀出資料,用輸出資料流輸出到頁面。
<%@ page contentType="text/html" language="java" %> 
<%@ page buffer="16kb" %> 
<%@ page import="java.sql.*"%> 
<%@ page import="java.io.*"%>
 <% int len = 10 * 1024 * 1024; 
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@10.168.8.99:1521:orafy"; //orcl為你的資料庫的SID String user="lhzy";
 String password="qwertyuiop"; 
Connection conn= DriverManager.getConnection(url,user,password); 
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select pic from test"; 
ResultSet rs=stmt.executeQuery(sql); //定位到記錄 rs.next(); 
InputStream in = rs.getBinaryStream(1);//① 
response.reset(); //返回在流中被標記過的位置 
response.setContentType("image/jpg"); //或gif等 //得到輸入資料流 
OutputStream toClient = response.getOutputStream();//② 
byte[] P_Buf = new byte[len];
 int i; 
while ((i = in.read(P_Buf)) != -1) 
{ 
toClient.write(P_Buf, 0, i); 
} in.close(); 
toClient.flush(); //強制清出緩衝區 
toClient.close();//② 
%> 
<% rs.close(); 
stmt.close(); 
conn.close(); %>
  需要注意的地方:
  需要注意的有兩個方面:①處的代碼如注意的是,在去記錄前要先調用next()函數,定位到第一個記錄,記錄中列的索引是從1開始的,不是從0開始。 ②處如果出錯,檢查是不是忘記寫流的關閉了。就是下面的那句。原因可能是,在其它的地方也調用了response.getOutputStread()。如果不關閉,這個調用是不能成功的。