您的位置:首页 > 数据库

如何在SQLServer中保存和输出图片

2008-04-26 09:27 295 查看
建表    为了试验这个例子你需要一个含有数据的table(你可以在现在的库中创建它,也可以创建一个新的),下面是它的结构: 
  ColumnName
  Datatype
  Purpose
  ID
  Integer
  identitycolumnPrimarykey
  IMGTITLE
  Varchar(50)
  Storessomeuserfriendlytitletoidentitytheimage
  IMGTYPE
  Varchar(50)
  Storesimagecontenttype.Thiswillbesameasrecognizedcontenttypesof
  IMGDATA
  Image
  Storesactualimageorbinarydata.
  保存images进数据库   为了保存图片到table你首先得从客户端上传它们到你的web服务器。你可以创建一个webform,用TextBox得到图片的标题,用FileServerControl得到图片文件。确信你设定了Form的encType属性为multipart/form-data。 
  Streamimgdatastream=File1.PostedFile.InputStream;
  intimgdatalen=File1.PostedFile.ContentLength;
  stringimgtype=File1.PostedFile.ContentType;
  stringimgtitle=TextBox1.Text;
  byte[]imgdata=newbyte[imgdatalen];
  intn=imgdatastream.Read(imgdata,0,imgdatalen);
  stringconnstr=
  ((NameValueCollection)Context.GetConfig
  ("appSettings"))["connstr"];
  SqlConnectionconnection=newSqlConnection(connstr);
  SqlCommandcommand=newSqlCommand
  ("INSERTINTOImageStore(imgtitle,imgtype,imgdata)
  VALUES(@imgtitle,@imgtype,@imgdata)",connection);
  SqlParameterparamTitle=newSqlParameter
  ("@imgtitle",SqlDbType.VarChar,50);
  paramTitle.Value=imgtitle;
  command.Parameters.Add(paramTitle);
  SqlParameterparamData=newSqlParameter
  ("@imgdata",SqlDbType.Image);
  paramData.Value=imgdata;
  command.Parameters.Add(paramData);
  SqlParameterparamType=newSqlParameter
  ("@imgtype",SqlDbType.VarChar,50);
  paramType.Value=imgtype;
  command.Parameters.Add(paramType);
  connection.Open();
  intnumRowsAffected=command.ExecuteNonQuery();
  connection.Close(); 
  privatevoidPage_Load(objectsender,System.EventArgse)  {  stringimgid=Request.QueryString["imgid"];  stringconnstr=((NameValueCollection)  Context.GetConfig("appSettings"))["connstr"];  stringsql="SELECTimgdata,imgtypeFROMImageStoreWHEREid="  +imgid;  SqlConnectionconnection=newSqlConnection(connstr);  SqlCommandcommand=newSqlCommand(sql,connection);  connection.Open();  SqlDataReaderdr=command.ExecuteReader();  if(dr.Read())  {  Response.ContentType=dr["imgtype"].ToString();  Response.BinaryWrite((byte[])dr["imgdata"]);  }  connection.Close();  }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: