使用.NET向SQL Server數(shù)據(jù)庫存取圖片
使用.NET向SQL Server數(shù)據(jù)庫存取圖片
使用.Net技術(shù),我們可以很方便的將圖片存入SQL Server數(shù)據(jù)庫中并方便的讀取顯示出來,詳細(xì)的實(shí)現(xiàn)方法我們一步一步將會(huì)了解到。先說如何將圖片存儲(chǔ)到sql server數(shù)據(jù)庫中:
.NET向SQL Server數(shù)據(jù)庫存取圖片技巧:存入圖片
使用asp.net將圖片上傳并存入SQL Server中,然后從SQL Server中讀取并顯示出來:
1)上傳并存入SQL Server
數(shù)據(jù)庫結(jié)構(gòu)
- create table test
- {
- id identity(1,1),
- FImage image
- }
相關(guān)的存儲(chǔ)過程
- Create proc UpdateImage
- (
- @UpdateImage Image
- )
- As
- Insert Into test(FImage) values(@UpdateImage)
- GO
在UpPhoto.aspx文件中添加如下:
- < input id="UpPhoto" name="UpPhoto" runat="server" type="file">
- < asp:Button id="btnAdd" name="btnAdd" runat="server" Text="上傳">< /asp:Button>
然后在后置代碼文件UpPhoto.aspx.cs添加btnAdd按鈕的單擊事件處理代碼:
- private void btnAdd_Click(object sender, System.EventArgs e)
- {
- //獲得圖象并把圖象轉(zhuǎn)換為byte[]
- HttpPostedFile upPhoto=UpPhoto.PostedFile;
- int upPhotoLength=upPhoto.ContentLength;
- byte[] PhotoArray=new Byte[upPhotoLength];
- Stream PhotoStream=upPhoto.InputStream;
- PhotoStream.Read(PhotoArray,0,upPhotoLength);
- //連接數(shù)據(jù)庫
- SqlConnection conn=new SqlConnection();
- conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";
- SqlCommand cmd=new SqlCommand("UpdateImage",conn);
- cmd.CommandType=CommandType.StoredProcedure;
- cmd.Parameters.Add("@UpdateImage",SqlDbType.Image);
- cmd.Parameters["@UpdateImage"].Value=PhotoArray;
- //如果你希望不使用存儲(chǔ)過程來添加圖片把上面四句代碼改為:
- //string strSql="Insert into test(FImage) values(@FImage)";
- //SqlCommand cmd=new SqlCommand(strSql,conn);
- //cmd.Parameters.Add("@FImage",SqlDbType.Image);
- //cmd.Parameters["@FImage"].Value=PhotoArray;
- conn.Open();
- cmd.ExecuteNonQuery();
- conn.Close();
- }
.NET向SQL Server數(shù)據(jù)庫存取圖片技巧:從SQL Server中讀取并顯示出來
在需要顯示圖片的地方添加如下代碼:
- < asp:image id="imgPhoto" runat="server" ImageUrl="ShowPhoto.aspx">< /asp:image>
ShowPhoto.aspx主體代碼:
- private void Page_Load(object sender, System.EventArgs e)
- {
- if(!Page.IsPostBack)
- {
- SqlConnection conn=new SqlConnection()
- conn.ConnectionString="Data Source=localhost;Database=test;User Id=sa;Pwd=sa";
- string strSql="select * from test where id=2";//這里假設(shè)獲取id為2的圖片
- SqlCommand cmd=new SqlCommand(strSql,conn);
- conn.Open();
- SqlDataReader reader=cmd.ExecuteReader();
- reader.Read();
- Response.ContentType="application/octet-stream";
- Response.BinaryWrite((Byte[])reader["FImage"]);
- Response.End();
- reader.Close();
- }
- }
以上就介紹了.NET向SQL Server數(shù)據(jù)庫存取圖片的實(shí)現(xiàn)方法。
【編輯推薦】