首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 數據庫知識 >  >> SQL Server 資料庫 >> 關於SqlServer

ASP.NET 從 SQL Server 讀取二進位圖片並繫結顯示於 DataGrid 完整實作

     編輯:關於SqlServer

核心架構

  • 資料庫:SQL Server,圖片儲存於 varbinary(max) / image 欄位
  • 前端:ASP.NET DataGrid / GridView
  • 關鍵技巧:獨立 HTTP Handler (ASHX) 串流輸出圖片,DataGrid 僅繫結圖片 ID,由 <asp:Image ImageUrl='Handler.ashx?id=...' /> 非同步載入

完整程式碼實作

1. 資料庫存取類別

// ReadImage.ashx.cs
public class ReadImage : IHttpHandler {
    public void ProcessRequest(HttpContext context) {
        string id = context.Request.QueryString["id"];
        if (string.IsNullOrEmpty(id)) return;

        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString)) {
            SqlCommand cmd = new SqlCommand("SELECT Photo FROM Employees WHERE EmployeeID = @id", conn);
            cmd.Parameters.AddWithValue("@id", id);
            conn.Open();
            byte[] imgBytes = cmd.ExecuteScalar() as byte[];
            if (imgBytes != null) {
                context.Response.ContentType = "image/jpeg";
                context.Response.BinaryWrite(imgBytes);
            }
        }
    }
    public bool IsReusable { get { return false; } }
}

2. DataGrid 頁面

<%@ Page Language="C#" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
    void Page_Load() {
        if (!IsPostBack) BindGrid();
    }
    void BindGrid() {
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnStr"].ConnectionString)) {
            SqlDataAdapter da = new SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, BirthDate FROM Employees", conn);
            DataTable dt = new DataTable();
            da.Fill(dt);
            DataGrid1.DataSource = dt;
            DataGrid1.DataBind();
        }
    }
    // 產生圖片 URL
    string FormatURL(object empID) {
        return "ReadImage.ashx?id=" + empID.ToString();
    }
</script>

<asp:DataGrid id="DataGrid1" runat="server" AutoGenerateColumns="False">
    <Columns>
        <asp:BoundColumn DataField="LastName" HeaderText="姓氏" />
        <asp:BoundColumn DataField="FirstName" HeaderText="名字" />
        <asp:BoundColumn DataField="BirthDate" HeaderText="出生日期" DataFormatString="{0:yyyy-MM-dd}" />
        <asp:TemplateColumn HeaderText="照片">
            <ItemTemplate>
                <asp:Image runat="server" ImageUrl='<%# FormatURL(DataBinder.Eval(Container.DataItem, "EmployeeID")) %>' Width="80" Height="100" />
            </ItemTemplate>
        </asp:TemplateColumn>
    </Columns>
</asp:DataGrid>

3. Web.config 連線字串

<connectionStrings>
    <add name="ConnStr" connectionString="Server=.;Database=Northwind;Integrated Security=SSPI;" />
</connectionStrings>

關鍵優勢

  • 分離關注點:頁面只負責資料呈現,圖片串流由專用 Handler 處理
  • 記憶體效率:避免將大量二進位資料載入 DataTable/ViewState
  • 快取友善:Handler 可輕鬆加入 Response.Cache 設定客戶端/Proxy 快取
  • 擴充性:支援動態縮圖、水印、權限驗證等進階處理

常見坑點與解決

問題原因解決
圖片顯示紅叉Handler 路徑錯誤 / ContentType 不對 / 資料為 NULL瀏覽器開發者工具檢查 Network 請求回應
DataGrid 分頁後圖片消失ViewState 未保留資料 / Handler 依賴 SessionHandler 僅依 QueryString,不依賴 Session
大圖載入慢無快取 / 原始檔過大資料庫存儲縮圖 / Handler 加入 OutputCache

現代化替代方案

ASP.NET Core / MVC / Razor Pages 建議改用:

  • Controller Action 回傳 File(byte[], contentType)
  • <img src="/api/images/@Model.Id" /> 前端繫結
  • 或採用 Blob 儲存體 + CDN 卸載頻寬
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved