Saving and displaying photos in SQL Server using ASP. NET and fileupload Control

Source: Internet
Author: User

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 );

}

}
}
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.