板橋房屋影音網

一位房仲與投資人的學習日誌

房產・科技・音樂・生活
持續學習・記錄生活・分享知識

insert圖檔至MS Sql


分享: facebook PLURK twitter
把FileUpload的檔案(圖檔)上傳至MS Sql中,然後從資料庫讀出後,利用ashx的泛型處理轉成二進位位元組,呈現在GridView中。



建置:

Create Table UploadImg(

id int identity(1,1),

images image null

)

上傳:

//上傳圖片

//定義位元組

byte[] imagebyte = new byte[this.FileUpload1.PostedFile.ContentLength];

//把fileupload載入位元組

imagebyte = FileUpload1.FileBytes;

cmd.Parameters.Add("@images", SqlDbType.Image).Value = imagebyte;

try

{

cn.Open();

cmd.ExecuteNonQuery().ToString();

}

catch (Exception Err)

{

}

finally

{

cn.Close();

}



File.ashx:負責把資料庫的圖檔轉成二進位

public void ProcessRequest (HttpContext context) {

int id = int.Parse(context.Request.QueryString["id"]);

using (SqlConnection conn = new SqlConnection(連線字串))

{

string sql = "select images from [upload] where id=@id";

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;

conn.Open();

SqlDataReader dr = cmd.ExecuteReader();

if (dr.Read())

{

context.Response.ContentType = "image/jpg";
context.Response.BinaryWrite((byte[])dr["Images"]);

}

dr.Close();

}

}

GridView的設定:只要指定圖片的來源路徑就ok了。
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id" >
<Columns>
<asp:BoundField DataField="id" HeaderText="ID" />
<asp:ImageField DataImageUrlField="id" DataImageUrlFormatString="file.ashx?id={0}"
HeaderText="Images">
</asp:ImageField>
</Columns>
</asp:GridView>
0
相關分類

留言 0 則公開留言

尚無公開留言。

※ 為維護留言品質,所有留言須經管理者審核後才會公開,請勿重複提交。

留言送出成功

感謝您的留言!待管理者審核後即會公開,請勿重複提交。