本文完整示範如何在 ASP.NET WebForms 環境中實作圖片上傳、二進位儲存至 SQL Server、DataGrid 列表顯示與動態圖片瀏覽功能。
在 SQL Server 2000 的 pubs 資料庫建立 ImageStore 資料表:
CREATE TABLE ImageStore (
ImgID INT IDENTITY(1,1) PRIMARY KEY,
ImageData IMAGE, -- 或 varbinary(MAX) (SQL 2005+)
ImageContentType VARCHAR(50), -- MIME 類型
ImageDescription VARCHAR(200), -- 描述
ImageSize BIGINT -- 檔案大小
)
<%@ Page Language="c#" Codebehind="processImage.aspx.cs" AutoEventWireup="false" Inherits="imageProcess.imageProcess" %>
圖片上傳管理
using System;
using System.Data.SqlClient;
using System.IO;
using System.Web.UI.WebControls;
namespace imageProcess
{
public class imageProcess : System.Web.UI.Page
{
protected HtmlInputFile File1;
protected TextBox txtDescript;
protected DataGrid DG_Persons;
protected Button btnUpload;
private void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) DataGridBind();
}
// 重新繫結 DataGrid
private void DataGridBind()
{
string connStr = "server=.;database=pubs;uid=sa;pwd=;";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
SqlCommand cmd = new SqlCommand(
"SELECT ImgID, ImageContentType, ImageSize, ImageData FROM ImageStore", conn);
DG_Persons.DataSource = cmd.ExecuteReader();
DG_Persons.DataBind();
}
}
// 上傳按鈕點擊事件
private void btnUpload_Click(object sender, EventArgs e)
{
string connStr = "server=.;database=pubs;uid=sa;pwd=;";
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
// 1. 讀取上傳檔案為位元組陣列
FileStream fs = File.Open(File1.PostedFile.FileName, FileMode.Open);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int)fs.Length);
fs.Close();
// 2. 參數化 INSERT 指令
string sql = @"INSERT INTO ImageStore
(ImageData, ImageContentType, ImageDescription, ImageSize)
VALUES (@Image, @FileType, @FileDesc, @FileSize)";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.Add("@Image", System.Data.SqlDbType.Image, buffer.Length).Value = buffer;
cmd.Parameters.Add("@FileType", System.Data.SqlDbType.VarChar, 50).Value = File1.PostedFile.ContentType;
cmd.Parameters.Add("@FileDesc", System.Data.SqlDbType.VarChar, 200).Value = txtDescript.Text;
cmd.Parameters.Add("@FileSize", System.Data.SqlDbType.BigInt).Value = File1.PostedFile.ContentLength;
cmd.ExecuteNonQuery();
}
}
// 3. 重新整理列表
DataGridBind();
}
// 產生動態圖片 URL
protected string FormatURL(object imgId)
{
return "ReadImage.aspx?id=" + imgId.ToString();
}
}
}
| 環節 | 核心 API/技術 | 注意事項 |
|---|---|---|
| 檔案上傳 | HtmlInputFile / File1.PostedFile | Form 必須 enctype="multipart/form-data" |
| 二進位讀取 | FileStream + byte[] | 大檔案建議分塊讀取避免 OOM |
| 資料庫儲存 | SqlParameter + SqlDbType.Image | 參數化查詢防注入,Image 型別已棄用建議 varbinary(MAX) |
| 動態圖片顯示 | Image.ImageUrl 指向 .aspx 處理器 | 分離圖片輸出邏輯,支援快取/權限控制 |
| DataGrid 模板 | TemplateColumn + DataBinder.Eval | 靈活控制每欄顯示邏輯 |
下一篇將實作 ReadImage.aspx 處理器,從資料庫讀取二進位資料並正確輸出圖片 HTTP 回應,完成完整閉環。