萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 資料庫 >> SQL Server 教學

SQL Server 中儲存與輸出圖片的完整實作

介紹

有時需將二進位資料 (圖片、文件) 存入資料庫。SQL Server 提供 image 資料類型供儲存二進位資料。本文示範如何在 SQL Server 中儲存與輸出圖片。

建表

建立測試表 ImageStore:

欄位名資料類型用途
IDInteger (identity)主鍵
IMGTITLEVarchar(50)圖片標題
IMGTYPEVarchar(50)圖片 MIME 類型
IMGDATAImage實際二進位資料

儲存圖片到 SQL Server

從客戶端上傳圖片到 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 來輸出二進位圖片資料。

copyright © 萬盛學電腦網 all rights reserved