<< 2025 年 5 月 >>
    123
45678910
11121314151617
18192021222324
25262728293031
回首頁 | 到今日 | 到本月

文章分類

最新文章

insert圖檔至MS Sql                          

2018/6/16 下午 02:06:35發表      點閱: 3993    推荐 :471                          


 

內容面板收納

分享: 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>
  推荐分享 推薦本文到Twitter推特去! 推薦本文到Plurk噗浪去! 推荐本文到 facebook臉書   
 

我要評論

標題
暱稱
郵件
內容
* 驗證碼