萬盛學電腦網

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

JSP 實現圖片資料庫存儲與動態顯示完整教程

場景動機

傳統做法將圖片存檔案系統,資料庫僅存路徑。若需動態生成圖片(如驗證碼、水印、權限控制),必須將二進位資料直接存入資料庫 BLOB 欄位,再由 JSP/Servlet 讀取輸出。

資料庫表結構(SQL Server 為例)

CREATE TABLE picturenews (
    id INT IDENTITY(1,1) PRIMARY KEY,
    image IMAGE NULL,              -- 二進位圖片資料
    content VARCHAR(500) NULL,     -- 簡介
    detail VARCHAR(5000) NULL      -- 詳細內容
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY];

核心實現步驟

  1. 上傳存入:表單 enctype="multipart/form-data",Servlet 使用 Part (Servlet 3.0) 或 Apache Commons FileUpload 解析,將輸入流寫入 PreparedStatement.setBinaryStream()。
  2. 讀取顯示:專用 Servlet(如 ShowImage?id=123)查詢 BLOB,設定 response.setContentType("image/jpeg"),將 ResultSet.getBinaryStream() 輸出至 response.getOutputStream()。
  3. JSP 引用:<img src="ShowImage?id=${news.id}" /> 即可動態顯示。

關鍵代碼片段(顯示 Servlet)

@WebServlet("/ShowImage")
public class ShowImage extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        try (Connection conn = DS.getConnection();
             PreparedStatement ps = conn.prepareStatement("SELECT image FROM picturenews WHERE id=?")) {
            ps.setString(1, id);
            try (ResultSet rs = ps.executeQuery()) {
                if (rs.next()) {
                    resp.setContentType("image/jpeg");
                    try (InputStream is = rs.getBinaryStream("image");
                         OutputStream os = resp.getOutputStream()) {
                        byte[] buf = new byte[4096];
                        int len;
                        while ((len = is.read(buf)) != -1) os.write(buf, 0, len);
                    }
                }
            }
        } catch (SQLException e) { throw new ServletException(e); }
    }
}

注意事項

  • 大型圖片建議存檔案系統,資料庫只存路徑,避免資料庫膨脹影響備份效能。
  • 輸出前檢測 MIME 類型,正確設定 Content-Type。
  • 生產環境需考慮快取策略(ETag、Last-Modified)減輕頻寬壓力。
copyright © 萬盛學電腦網 all rights reserved