在 ASP.NET Web Forms 中,System.Web.UI.WebControls.Image 控制項無法像 Windows Forms 那樣直接接受 byte[] 資料流來顯示圖片。因為 ImageUrl 屬性只接受 URL 字串,無法直接繫結二進位資料。為了解決這個限制,常見的做法是採用「曲線救國」的策略:建立一個專門輸出圖片二進位流的獨立頁面(如 pic.aspx),再將主頁面中 Image 控制項的 ImageUrl 指向該頁面並帶上必要參數。
teacherdetial.aspx):負責呈現文字資料與 Image 控制項。pic.aspx):接收參數、從資料庫讀取二進位圖片、以 Response.BinaryWrite 輸出。<asp:Image ID="Image1" runat="server" Width="80" Height="80" />
protected void Page_Load(object sender, EventArgs e)
{
string tid = Request.Params["tid"];
this.Image1.ImageUrl = "~/teacher/pic.aspx?tid=" + tid;
}
pic.aspx 本身不需要任何 HTML 標記,只需在 Page_Load 中輸出二進位資料:
protected void Page_Load(object sender, EventArgs e)
{
string tid = Request.Params["tid"].ToString();
TeacherDao td = new TeacherDao();
Response.BinaryWrite(td.getPic(tid));
}
Response.ContentType = "image/jpeg"(或 png/gif),確保瀏覽器正確解碼。Response.Cache.SetCacheability(HttpCacheability.Public) 等標頭,減少重複請求。此模式適用於「圖片儲存於資料庫 BLOB 欄位」且「需在 GridView、Repeater、DetailsView 等資料繫結控制項中顯示」的傳統 Web Forms 專案。若為 ASP.NET Core / MVC 專案,建議改用 FileResult 或 PhysicalFileResult 直接回傳檔案流,架構更簡潔。