有時需將二進位資料 (圖片、文件) 存入資料庫。SQL Server 提供 image 資料類型供儲存二進位資料。本文示範如何在 SQL Server 中儲存與輸出圖片。
建立測試表 ImageStore:
| 欄位名 | 資料類型 | 用途 |
|---|---|---|
| ID | Integer (identity) | 主鍵 |
| IMGTITLE | Varchar(50) | 圖片標題 |
| IMGTYPE | Varchar(50) | 圖片 MIME 類型 |
| IMGDATA | Image | 實際二進位資料 |
從客戶端上傳圖片到 Web 伺服器,建立 Web Form,使用 TextBox 取標題,File Server Control 取檔案。注意設定 Form 的 encType="multipart/form-data"。
Stream imgdatastream = File1.PostedFile.InputStream;
int imgdatalen = File1.PostedFile.ContentLength;
string imgtype = File1.PostedFile.ContentType;
string imgtitle = TextBox1.Text;
byte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata, 0, imgdatalen);
string connstr = ConfigurationSettings.AppSettings["connstr"];
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(
"INSERT INTO ImageStore(imgtitle, imgtype, imgdata) VALUES (@imgtitle, @imgtype, @imgdata)", connection);
command.Parameters.Add(new SqlParameter("@imgtitle", SqlDbType.VarChar, 50) { Value = imgtitle });
command.Parameters.Add(new SqlParameter("@imgtype", SqlDbType.VarChar, 50) { Value = imgtype });
command.Parameters.Add(new SqlParameter("@imgdata", SqlDbType.Image) { Value = imgdata });
connection.Open();
int numRowsAffected = command.ExecuteNonQuery();
connection.Close();
直接將圖片輸出至瀏覽器:
private void Page_Load(object sender, System.EventArgs e) {
string imgid = Request.QueryString["imgid"];
string connstr = ConfigurationSettings.AppSettings["connstr"];
string sql = "SELECT imgdata, imgtype FROM ImageStore WHERE id = " + imgid;
SqlConnection connection = new SqlConnection(connstr);
SqlCommand command = new SqlCommand(sql, connection);
connection.Open();
SqlDataReader dr = command.ExecuteReader();
if (dr.Read()) {
Response.ContentType = dr["imgtype"].ToString();
Response.BinaryWrite((byte[])dr["imgdata"]);
}
connection.Close();
}
關鍵在於使用 Response.BinaryWrite 而非 Response.Write 來輸出二進位圖片資料。