SQL Server provides a special data type: image, which is a type that contains binary data. The following example shows how to put text or photos in the database. In this article, we will see how to store and read images in SQL Server.
1. Create a table:
Create a table with the following structure in SQL Server:
Column name type objective
Id integer primary key ID
Imgtitle varchar (50) image title
Imgtype varchar (50) image type. ASP. NET to be identified type
Imgdata image is used to store binary data.
2. store images in the SQL Server database
To store tables, you must first upload them to your web server. You can develop a web form, it is used to import images from textbox Web Control in the client to your web server. Set your enctype attribute to myltipart/formdata.
Stream imgdatastream = file1.postedfile. inputstream;
Int imgdatalen = file1.postedfile. contentlength;
String imgtype = file1.postedfile. contenttype;
String imgtitle = textbox1.text;
Byte [] imgdata = new byte [imgdatalen];
Int n = imgdatastream. Read (imgdata, 0, imgdatalen );
String connstr = (namevaluecollection) Context. getconfig ("etettings") ["connstr"];
Sqlconnection connection = new sqlconnection (connstr );
Sqlcommand command = new sqlcommand
("Insert into imagestore (imgtitle, imgtype, imgdata)
Values (@ imgtitle, @ imgtype, @ imgdata) ", connection );
Sqlparameter paramtitle = new sqlparameter
("@ Imgtitle", sqldbtype. varchar, 50 );
Paramtitle. value = imgtitle;
Command. Parameters. Add (paramtitle );
Sqlparameter paramdata = new sqlparameter ("@ imgdata", sqldbtype. Image );
Paramdata. value = imgdata;
Command. Parameters. Add (paramdata );
Sqlparameter paramtype = new sqlparameter ("@ imgtype", sqldbtype. varchar, 50 );
Paramtype. value = imgtype;
Command. Parameters. Add (paramtype );
Connection. open ();
Int numrowsaffected = command. executenonquery ();
Connection. Close ();
3. Restore read from the database
Now let's read the data we put from SQL server! We will output the image to your browser, and you can store it to your desired location.
Private void page_load (Object sender, system. eventargs E)
{
String imgid = request. querystring ["imgid"];
String connstr = (namevaluecollection)
Context. getconfig ("etettings") ["connstr"];
String SQL = "select imgdata, imgtype from imagestore where id =" + imgid;
Sqlconnection connection = new sqlconnection (connstr );
Sqlcommand command = new sqlcommand (SQL, connection );
Connection. open ();
Sqldatareader DR = command. executereader ();
If (dr. Read ())
{
Response. contenttype = Dr ["imgtype"]. tostring ();
Response. binarywrite (byte []) Dr ["imgdata"]);
}
Connection. Close ();
}
Note that response. binarywrite is not response. Write.