asp.net在sqlserver中的图片存取技术
在使用asp.net将图片上传并存入sqlserver中,然后从sqlserver中读取并显示出来
一,上传并存入sqlserver
数据库结构
create table test
{
id identity(1,1),
fimage image
}
相关的存储过程
create proc updateimage
(
@updateimage image
)
as
insert into test(fimage) values(@updateimage)
go
在upphoto.aspx文件中添加如下:
<input id=”upphoto” name=”upphoto” runat=”server” type=”file”>
<asp:button id=”btnadd” name=”btnadd” runat=”server” text=”上传”></asp:button>
然后在后置代码文件upphoto.aspx.cs添加btnadd按钮的单击事件处理代码:
private void btnadd_click(object sender, system.eventargs e)
{
//获得图象并把图象转换为byte[]
httppostedfile upphoto=upphoto.postedfile;
int upphotolength=upphoto.contentlength;
byte[] photoarray=new byte[upphotolength];
stream photostream=upphoto.inputstream;
photostream.read(photoarray,0,upphotolength);
//连接数据库
sqlconnection conn=new sqlconnection();
conn.connectionstring=”data source=localhost;database=test;user id=sa;pwd=sa”;
sqlcommand cmd=new sqlcommand(“updateimage”,conn);
cmd.commandtype=commandtype.storedprocedure;
cmd.parameters.add(“@updateimage”,sqldbtype.image);
cmd.parameters[“@updateimage”].value=photoarray;
//如果你希望不使用存储过程来添加图片把上面四句代码改为:
//string strsql=”insert into test(fimage) values(@fimage)”;
//sqlcommand cmd=new sqlcommand(strsql,conn);
//cmd.parameters.add(“@fimage”,sqldbtype.image);
//cmd.parameters[“@fimage”].value=photoarray;
conn.open();
cmd.executenonquery();
conn.close();
}
二,从sqlserver中读取并显示出来
在需要显示图片的地方添加如下代码:
<asp:image id=”imgphoto” runat=”server” imageurl=”showphoto.aspx”></asp:image>
showphoto.aspx主体代码:
private void page_load(object sender, system.eventargs e)
{
if(!page.ispostback)
{
sqlconnection conn=new sqlconnection()
conn.connectionstring=”data source=localhost;database=test;user id=sa;pwd=sa”;
string strsql=”select * from test where id=2″;//这里假设获取id为2的图片
sqlcommand cmd=new sqlcommand()
reader.read();
response.contenttype=”application/octet-stream”;
response.binarywrite((byte[])reader[“fimage”]);
response.end();
reader.close();
}
}