Upload an image to SQL Server and save it as an image
Protected void button#click (Object sender, eventargs E)
{
Httppostedfile post = imginput. postedfile;
Int lent = post. contentlength;
Byte [] lentimg = new byte [lent];
Stream photostream = post. inputstream;
Photostream. Read (lentimg, 0, lent );
Sqlcommand sqlcom = new sqlcommand ("insert into zhaoxiaomingpic values (@ IMG)", con );
Sqlcom. Parameters. Add ("@ IMG", sqldbtype. Image );
Sqlcom. Parameters ["@ IMG"]. value = lentimg;
Con. open ();
Sqlcom. executenonquery ();
Con. Close ();
}
Read data from an image-type table.
// Web Part
String STR = configurationsettings. deleettings ["connstring"]. tostring ();
Sqlconnection con = new sqlconnection (STR );
String SQL = "select personimage, personimagetype from person where personemail = '" + session ["email"] + "'";
Sqlcommand cmd = new sqlcommand (SQL, con );
Con. open ();
Sqldatareader DR = cmd. executereader ();
Byte [] picturedata = NULL;
While (dr. Read ())
{
Picturedata = (byte []) Dr [0];
Response. contenttype = Dr [1]. tostring ();
}
This. enableviewstate = false;
Response. appendheader ("contect-length", picturedata. length. tostring ());
Response. binarywrite (picturedata );
Response. End ();
//CodeWrite a show. ASP page,
// Load an image control on the called page,
// Call the code: This. image1.imageurl = "show. aspx ";
// Winfrom
String strcon = "Data Source = AAAA; initial catalog = school; uid = sa; Pwd = ";
Sqlconnection con = new sqlconnection (strcon );
Con. open ();
String SQL = "select personimage from person where personid =" + this. textbox1.text + "";
Sqlcommand cmd = new sqlcommand (SQL, con );
Sqldatareader DR = cmd. executereader ();
If (dr. hasrows)
{
Dr. Read ();
Byte [] IMG = (byte []) Dr ["personimage"];
Memorystream MS = new memorystream ();
Ms. Write (IMG, 0, IMG. Length );
This. picturebox1.image = image. fromstream (MS );
Ms. Close ();
}
Dr. Close ();