前提:使用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()。如果不關閉,這個調用是不能成功的。
新聞熱點
疑難解答