歡迎您光臨本站 註冊首頁

在SQL Server中保存和輸出圖片

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0
   建表   

   為了試驗這個例子你需要一個含有數據的table(你可以在現在的庫中創建它,也可以創建一個新的資料庫),下面是它的結構:  

   Column Name
   Datatype
   Purpose
   ID
   Integer
   identity column Primary key
   IMGTITLE
   Varchar(50)
   Stores some user friendly title to identity the image
   IMGTYPE
   Varchar(50)
   Stores image content type. This will be same as recognized content types of ASP.NET
   IMGDATA
   Image
   Stores actual image or binary data.

   保存images進SQL Server資料庫  

   為了保存圖片到table你首先得從客戶端上傳它們到你的web伺服器.你可以創建一個web form,用TextBox得到圖片的標題,用HTML 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=
   ((NameValueCollection)Context.GetConfig
   ("appSettings"))["connstr"];
   SqlConnection connection = new SqlConnection(connstr);
   SqlCommand command = new SqlCommand
   ("INSERT INTO ImageStore(imgtitle,imgtype,imgdata)
   VALUES ( @imgtitle, @imgtype,@imgdata )", connection );
   SqlParameter paramTitle = new SqlParameter
   ("@imgtitle", SqlDbType.VarChar,50 );
   paramTitle.Value = imgtitle;
   command.Parameters.Add( paramTitle);
   SqlParameter paramData = new SqlParameter
   ( "@imgdata", SqlDbType.Image );
   paramData.Value = imgdata;
   command.Parameters.Add( paramData );
   SqlParameter paramType = new SqlParameter
   ( "@imgtype", SqlDbType.VarChar,50 );
   paramType.Value = imgtype;
   command.Parameters.Add( paramType );
   connection.Open();
   int numRowsAffected = command.ExecuteNonQuery();
   connection.Close();   

   從資料庫中輸出圖片   

   現在讓我們從資料庫中取出我們剛剛保存的圖片,在這兒,我們將直接將圖片輸出至瀏覽器.你也可以將它保存為一個文件或做任何你想做的.  

   private void Page_Load(object sender, System.EventArgs e)
   {
   string imgid =Request.QueryString["imgid"];
   string connstr=((NameValueCollection)
   Context.GetConfig("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();
   }   

   在上面的代碼中我們使用了一個已經打開的資料庫,通過datareader選擇images.接著用Response.BinaryWrite代替Response.Write來顯示image文件.


[火星人 ] 在SQL Server中保存和輸出圖片已經有643次圍觀

http://coctec.com/docs/linux/show-post-58210.html