萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> JSP 程式設計

JSP 從資料庫讀取圖片並輸出至瀏覽器

核心流程

  1. JDBC 連線資料庫,查詢含 BLOB 欄位的記錄
  2. 從 ResultSet 取得 InputStream(getBinaryStream(1))
  3. 設定響應頭 Content-Type: image/jpg(或 gif/png)
  4. 獲取 response.getOutputStream(),以位元組陣列緩衝寫入
  5. 關閉流與資料庫資源

完整 JSP 代碼

<%@ page contentType="text/html" language="java" %>
<%@ page buffer="16kb" %>
<%@ page import="java.sql.*, java.io.*" %>
<%
    int len = 10 * 1024 * 1024; // 10MB 緩衝
    Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
    String url = "jdbc:oracle:thin:@10.168.8.99:1521:orafy";
    Connection conn = DriverManager.getConnection(url, "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/jpg");
    OutputStream toClient = response.getOutputStream(); // ②

    byte[] buf = new byte[len];
    int bytesRead;
    while ((bytesRead = in.read(buf)) != -1) {
        toClient.write(buf, 0, bytesRead);
    }
    in.close();
    toClient.flush();
    toClient.close(); // ② 必須關閉,否則後續 getOutputStream() 會失敗

    rs.close();
    stmt.close();
    conn.close();
%>

關鍵注意點

  • ① rs.next() 不可省略:游標初始在第一行之前,必須先移動到有效行。
  • ② 流必須關閉:若同一請求多次獲取 response.getOutputStream(),未關閉會導致 IllegalStateException。
  • 列索引從 1 開始,非 0。
  • 生產環境建議:使用連線池、預編譯語句、適當緩衝區大小、異常處理與資源釋放放入 finally 或 try-with-resources。
copyright © 萬盛學電腦網 all rights reserved