介绍
有时候我们需要保存一些binary data进数据库
。SQL Server提供一个叫做image的特殊数据类型供我们保存binary data
。Binary data可以是图片、文档等。在这篇文章中我们将看到如何在
SQL Server中保存和输出图片。
建表
为了试验这个例子你需要一个含有数据的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 A.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。
tream imgdatastream = File1.PostedFile.IutStream;
int imgdatalen = File1.PostedFile.ContentLength;
tring imgtype = File1.PostedFile.ContentType;
tring imgtitle = TextBox1.Text;
yte[] imgdata = new byte[imgdatalen];
int n = imgdatastream.Read(imgdata,0,imgdatalen);
tring cotr=
((NameValueCollection)Context.GetConfig
("aettings"))["cotr"];
qlCoection coection = new SqlCoection(cotr);
qlCommand command = new SqlCommand
("IERT INTO ImageStore(imgtitle,imgtype,imgdata)
VALUES ( @imgtitle, @imgtype,@imgdata )", coection );
qlParameter paramTitle = new SqlParameter
("@imgtitle", SqlDbType.VarChar,50 );
aramTitle.Value = imgtitle;
command.Parameters.Add( paramTitle);
qlParameter paramData = new SqlParameter
( "@imgdata", SqlDbType.Image );
aramData.Value = imgdata;
command.Parameters.Add( paramData );
qlParameter paramType = new SqlParameter
( "@imgtype", SqlDbType.VarChar,50 );
aramType.Value = imgtype;
command.Parameters.Add( paramType );
coection.Open();
int numRowsAffected = command.ExecuteNonQuery();
coection.Close();
从数据库中输出图片
现在让我们从数据库中取出我们刚刚保存的图片,在这儿,我们将直接将图片输出至浏览器。你也可以将它保存为一个文件或做任何你想做的。
rivate void Page_Load(object sender, System.EventArgs e)
#123;
tring imgid =Request.QueryString["imgid"];
tring cotr=((NameValueCollection)
Context.GetConfig("aettings"))["cotr"];
tring sql="SELECT imgdata, imgtype FROM ImageStore WHERE id = "
+ imgid;
qlCoection coection = new SqlCoection(cotr);
qlCommand command = new SqlCommand(sql, coection);
coection.Open();
qlDataReader dr = command.ExecuteReader();
if(dr.Read())
#123;
Reoe.ContentType = dr["imgtype"].ToString();
Reoe.BinaryWrite( (byte[]) dr["imgdata"] );
#125;
coection.Close();
#125;
在上面的代码中我们使用了一个已经打开的数据库,通过datareader选择images。接着用Reoe.BinaryWrite代替Reoe.Write来显示image文件。
希望您喜欢这些文章,如有任何意见和建议请致信webmaster@bipinjoshi.com。
希望这篇
在SQL Server中保存和输出图片的文章能够对您有所帮助,如果您觉得这篇网站维护教程有用的话,别忘了推荐给您的朋友哦!如果您有好的经验方法,不妨拿出来和大家一起分享:假如每个人都拿出一个经验,那么我们都将额外的获取一堆他人的经验。
请记住本站永久域名:(黑客防线网安服务器维护方案维护基地)Www.Rongsen.Com.Cn