如何从数据库中读取并显示图片。
[此贴子已经被作者于2006-7-23 16:45:54编辑过]
以下有一些代码可以参考一下:
存储图片到SQL SERVER数据库中
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,command);
connection.open();
sqldatareader dr=command.executereader();
if(dr.read())
{
response.contenttype=dr["imgtype"].tostring();
response.binarywrite((byte[])dr["imgdata"]);
}
connection.close();
}