Original article: Saving and displaying photos in SQL Server using ASP. NET and fileupload Control
This article mainly introduces how to store images directly to the database in vs2005. Of course, the fileupload control is used.
Below I will focus onCodePost it (tested, no problem ):
Save:
Protected Void Button#click ( Object Sender, eventargs E)
{
If (Fileupload1.hasfile)
{
Using (Binaryreader Reader = New Binaryreader (fileupload1.postedfile. inputstream ))
{
Byte [] Image = Reader. readbytes (fileupload1.postedfile. contentlength );
Using (Sqlconnection Conn = New Sqlconnection ( " Server =.; database = ibatisnet; uid = sa; Pwd = " ))
{
Using (Sqlcommand command = Conn. createcommand ())
{
Command. commandtext = @" Insert into photo (photo) values (@ photo) " ;
Command. Parameters. addwithvalue ( " @ Photo " , Image );
Conn. open ();
Command. executenonquery ();
}
}
}
}
}
Display:
Protected Void Button2_click ( Object Sender, eventargs E)
{
Response. Clear ();
Response. contenttype = " Image/JPEG " ;
Using (Sqlconnection Conn = New Sqlconnection ( " Server =.; database = ibatisnet; uid = sa; Pwd = " ))
{
Using (Sqlcommand command = Conn. createcommand ())
{
Command. commandtext = " Select top 1 photo from photo " ;
Conn. open ();
Byte [] Imagedata = ( Byte []) Command. executescalar ();
Response. binarywrite (imagedata );
}
}
}