Asp.net: How to save SQL Server images and display images

Source: Internet
Author: User

/Asp tutorial. net how to save SQL server and display images

Private void form1_load (object sender, eventargs e)
{
Filestream fs = new filestream (@ "c: e06d3510ebfde555cb80c4de.jpg", filemode. open );
Int ilength = int. parse (fs. length. tostring (); // obtain the length of the current file.
Byte [] filebyte = new byte [ilength]; // creates an array of byte [] to save the file content
Fs. read (filebyte, 0, ilength); // read the object content to the byte [] array through the read method.
Fs. dispose ();
Sqlconnection conn = new sqlconnection (@ "server = localhost; integrated security = sspi; initial catalog = qq ");
// Insert database tutorial
String strsql = "insert into tbl_image (img) values (@ img )";
Sqlcommand cmd = new sqlcommand (strsql, conn );
Cmd. parameters. add ("@ img", sqldbtype. image, ilength). value = filebyte;
// The parameter value of the image saved by the value assignment, which is sqldbtype. binary
Conn. open (); // open the connection
Cmd.exe cutenonquery (); // execute the command
Conn. close ();

}


// Display images in the database

Private void button#click (object sender, eventargs e)
{
Byte [] filecontent;
Using (sqlconnection conn = new sqlconnection (@ "server = localhost; integrated security = sspi; initial catalog = qq "))
{
String strsql = "select img from tbl_image ";
Sqlcommand cmd = new sqlcommand (strsql, conn );
Conn. open ();
Sqldatareader dr = cmd.exe cutereader ();
// The preceding steps complete the execution of General sqlcommand commands,
// Returns a sqldatareader that assigns the image content to a byte [] array.
If (dr. read ())
{
Filecontent = (byte []) dr ["img"];
}
Else
{
Filecontent = new byte [0];
}
Dr. close ();
}
Memorystream MS = new memorystream (filecontent, 0, filecontent. length );
This. pbshowimage. image = image. fromstream (MS );
// Disable the memory stream
Ms. close ();
}

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.