傳統做法將圖片存檔案系統,資料庫僅存路徑。若需動態生成圖片(如驗證碼、水印、權限控制),必須將二進位資料直接存入資料庫 BLOB 欄位,再由 JSP/Servlet 讀取輸出。
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];
enctype="multipart/form-data",Servlet 使用 Part (Servlet 3.0) 或 Apache Commons FileUpload 解析,將輸入流寫入 PreparedStatement.setBinaryStream()。ShowImage?id=123)查詢 BLOB,設定 response.setContentType("image/jpeg"),將 ResultSet.getBinaryStream() 輸出至 response.getOutputStream()。<img src="ShowImage?id=${news.id}" /> 即可動態顯示。@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); }
}
}
Content-Type。