sqlserver图片:在SQL Server中保存和输出图片



介绍


有时候我们需要保存些binary data进数据库SQL Server提供个叫做image特殊数据类型供我们保存binary dataBinary 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 ASP.NET

IMGDATA
Image
Stores actual image or binary data.




保存images进SQL Server数据库


为了保存图片到table你首先得从客户端上传它们到你web服务器你可以创建个web form用TextBox得到图片标题用HTML File Server Control得到图片文件确信你设定了FormencType属性为multipart/form-data


Stream imgdatastream = File1.PostedFile.InputStream;

imgdatalen = File1.PostedFile.ContentLength;

imgtype = File1.PostedFile.ContentType;

imgtitle = TextBox1.Text;

imgdata = [imgdatalen];

n = imgdatastream.Read(imgdata,0,imgdatalen);

connstr=

((NameValueCollection)Context.GetConfig

(\"appSettings\"))[\"connstr\"];

SqlConnection connection = SqlConnection(connstr);

SqlCommand command = SqlCommand

(\"INSERT INTO ImageStore(imgtitle,imgtype,imgdata)

VALUES ( @imgtitle, @imgtype,@imgdata )\", connection );



SqlParameter paramTitle = SqlParameter

(\"@imgtitle\", SqlDbType.VarChar,50 );

paramTitle.Value = imgtitle;

command.Parameters.Add( paramTitle);



SqlParameter paramData = SqlParameter

( \"@imgdata\", SqlDbType.Image );

paramData.Value = imgdata;

command.Parameters.Add( paramData );



SqlParameter paramType = SqlParameter

( \"@imgtype\", SqlDbType.VarChar,50 );

paramType.Value = imgtype;

command.Parameters.Add( paramType );



connection.Open;

numRowsAffected = command.ExecuteNonQuery;

connection.Close;



从数据库中输出图片



现在让我们从数据库中取出我们刚刚保存图片在这儿我们将直接将图片输出至浏览器你也可以将它保存为个文件或做任何你想做



private void Page_Load(object sender, .EventArgs e)

{

imgid =Request.QueryString[\"imgid\"];

connstr=((NameValueCollection)

Context.GetConfig(\"appSettings\"))[\"connstr\"];

sql=\"SELECT imgdata, imgtype FROM ImageStore WHERE id = \"

+ imgid;

SqlConnection connection = SqlConnection(connstr);

SqlCommand command = SqlCommand(sql, connection);

connection.Open;

SqlDataReader dr = command.ExecuteReader;

(dr.Read)

{

Response.ContentType = dr[\"imgtype\"].;

Response.BinaryWrite( () dr[\"imgdata\"] );

}

connection.Close;

}



在上面代码中我们使用了个已经打开数据库通过datareader选择images接着用Response.BinaryWrite代替Response.Write来显示image文件


Tags:  sqlserver2005 sqlserver2000 sqlserver sqlserver图片

延伸阅读

最新评论

发表评论