首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> ASP.NET 基礎

ASP.NET 上傳圖片至 SQL Server 資料庫並讀取顯示完整教學

     編輯:ASP.NET 基礎

資料庫表結構

建立 ImageStore 表,使用 image 型別儲存二進位圖片資料(SQL Server 2005/2008 建議改用 varbinary(max))。

CREATE TABLE [dbo].[ImageStore] (
    [ImageID] [int] IDENTITY(1,1) NOT NULL,
    [ImageData] [image] NULL,
    [ImageContentType] [varchar](50) NULL,
    [ImageDescription] [varchar](200) NULL,
    [ImageSize] [int] NULL
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

上傳頁面(UpLoadImage.aspx + .cs)

前端表單

重點:<form ENCTYPE="multipart/form-data" runat="server"> 必須設定 enctype,<input type="file" runat="server" id="UP_FILE"> 供用戶選檔。

後端核心邏輯

protected void Button_Submit(object sender, EventArgs e) {
    HttpPostedFile UpFile = UP_FILE.PostedFile;
    int FileLength = UpFile.ContentLength;
    if (FileLength == 0) { txtMessage.Text = "請選擇檔案"; return; }

    byte[] FileByteArray = new byte[FileLength];
    UpFile.InputStream.Read(FileByteArray, 0, FileLength);

    using (SqlConnection conn = new SqlConnection(connStr)) {
        string sql = @"INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize)
                       VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@Image", SqlDbType.Image, FileLength).Value = FileByteArray;
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50).Value = UpFile.ContentType;
        cmd.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200).Value = txtDescription.Text;
        cmd.Parameters.Add("@ImageSize", SqlDbType.Int).Value = FileLength;
        conn.Open();
        cmd.ExecuteNonQuery();
        txtMessage.Text = "上傳成功!";
    }
}

讀取顯示頁面(ReadImage.aspx + .cs)

此頁面不輸出 HTML,直接輸出圖片二進位流,供 <img src="ReadImage.aspx?ImgID=1"> 引用。

public void Page_Load(object sender, EventArgs e) {
    int imgId = Convert.ToInt32(Request.QueryString["ImgID"]);
    using (SqlConnection conn = new SqlConnection(connStr)) {
        string sql = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
        SqlCommand cmd = new SqlCommand(sql, conn);
        cmd.Parameters.Add("@ImageID", SqlDbType.Int).Value = imgId;
        conn.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.Read()) {
            Response.ContentType = dr["ImageContentType"].ToString();
            Response.OutputStream.Write((byte[])dr["ImageData"], 0, (int)dr["ImageSize"]);
            Response.End();
        }
    }
}

前端引用示例

<img src="ReadImage.aspx?ImgID=1" alt="資料庫圖片" />

進階建議與最佳實務

  • 型別選擇:SQL Server 2008+ 請使用 varbinary(max) 取代已淘汰的 image 型別。
  • 大檔案處理:超過 1MB 圖片建議存檔案系統/Blob Storage,資料庫僅存路徑;或啟用 FILESTREAM。
  • 參數化查詢:範例已使用 SqlParameter 防止 SQL 注入。
  • 錯誤處理:正式環境需加入 try/catch/finally 並記錄日誌,避免連線洩漏。
  • 快取策略:ReadImage.aspx 可輸出 ETag/Last-Modified,配合瀏覽器快取減少資料庫負載。

總結

本文示範了 ASP.NET Web Forms 將圖片以二進位方式存入 SQL Server,並以獨立 .aspx 當作圖片 Handler 輸出的經典作法。雖然現代架構傾向物件儲存(Azure Blob、AWS S3)+ CDN,但理解資料庫二進位存取流程對維護舊系統、處理小型二進位資料仍有參考價值。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved