在 Web 應用中,圖片常儲存於資料庫 BLOB 欄位。JSP 需以 response.getOutputStream() 輸出二進位流,並正確設定 Content-Type,瀏覽器才能正確渲染。本文梳理核心步驟與易踩的坑。
<%@ page import="java.sql.*,java.io.*" %>
<%
int len = 10 * 1024 * 1024; // 10MB 緩衝
Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:@10.168.8.99:1521:orafy", "lhzy", "qwertyuiop");
Statement stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT pic FROM test");
rs.next(); // 必須先定位到第一筆
InputStream in = rs.getBinaryStream(1); // 索引從 1 開始
response.reset();
response.setContentType("image/jpeg"); // 或 image/png, image/gif
OutputStream toClient = response.getOutputStream();
byte[] buf = new byte[len];
int readBytes;
while ((readBytes = in.read(buf)) != -1) {
toClient.write(buf, 0, readBytes);
}
in.close();
toClient.flush();
toClient.close(); // 關閉輸出流,否則後續 response 可能失效
rs.close(); stmt.close(); conn.close();
%>
next():游標初始位於第一筆之前,直接 getBinaryStream 會拋異常;欄位索引從 1 起算,非 0。OutputStream:若同一請求中多處呼叫 response.getOutputStream() 卻未關閉前一個,後續呼叫會失敗。良習:用完即 close(),並在 finally 區塊釋放資料庫資源。