在許多應用場景中,為了保護敏感資料不被輕易竊取,將圖片直接儲存在資料庫而非檔案系統是常見需求。本文將詳細示範如何在 ASP.NET 中將圖片上傳並存入 SQL Server 2000 的 image 欄位,涵蓋前端表單設定、後端串流處理、檔案屬性擷取等關鍵步驟。
enctype="multipart/form-data",才能正確傳送二進位檔案資料。<input type="file"> 控制項,讓使用者選取欲上傳的圖片。System.IO 命名空間以操作串流物件。image 資料型別欄位的資料表。varchar 欄位儲存圖片的 MIME 類型(如 image/jpeg),方便後續輸出時設定正確的 Content-Type。在提交按鈕的 Click 事件中,透過 HttpPostedFile 物件取得上傳檔案的輸入串流、長度與類型,再以參數化查詢寫入資料庫:
protected void btnUpload_Click(object sender, EventArgs e)
{
if (fileUpload.HasFile)
{
HttpPostedFile postedFile = fileUpload.PostedFile;
int fileLength = postedFile.ContentLength;
byte[] imageData = new byte[fileLength];
postedFile.InputStream.Read(imageData, 0, fileLength);
string contentType = postedFile.ContentType;
string connStr = ConfigurationManager.ConnectionStrings["SqlConn"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connStr))
{
string sql = "INSERT INTO Images (ImageData, ContentType) VALUES (@ImageData, @ContentType)";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.Add("@ImageData", SqlDbType.Image).Value = imageData;
cmd.Parameters.Add("@ContentType", SqlDbType.VarChar, 50).Value = contentType;
conn.Open();
cmd.ExecuteNonQuery();
}
lblMessage.Text = "圖片上傳成功!";
}
}
HttpPostedFile.InputStream 屬性提供唯讀串流,可直接讀取上傳檔案的原始位元組,避免先存至伺服器磁碟再讀取的額外 I/O 開銷。
採用 SqlParameter 傳遞二進位資料,不僅安全,也能正確處理大型二進位物件(BLOB)。
若需從資料庫讀取並顯示圖片,可建立獨立的 ShowImage.aspx,依查詢字串取得圖片 ID,設定 Response.ContentType 並輸出 Response.BinaryWrite 即可。
將圖片存入資料庫能集中管理權限、備份與同步,配合參數化指令與串流處理,即可在 ASP.NET 中安全、高效地完成圖片儲存。