Note: This series records the problems encountered in my actual development and the collection of some technical articles.
We all know that in the GridView can not directly to bind to the image of the database, we can use HttpHandler very easy to complete this task, here I record this process.
1. Upload images to the database
Create a table in the database and add 3 fields:
Step one: Drag a FileUpload control in the Web page, a text box to enter the name and submit the upload button
<asp:FileUpload ID="fuImage" runat="server" /><br />
<asp:TextBox ID="txtImageName" runat="server"/><br />
<asp:Button ID="btnUpload" runat="server"
OnClick="btnUpload_Click" Text="Upload" />
Step Two: Configure the connection string within the Web.config file.
<add name="ConnectionString" connectionString="Data Source=.\SQLEXPRESS;
AttachDbFilename=|DataDirectory|\Image.mdf;Integrated Security=True;
User Instance=True" providerName="System.Data.SqlClient"/>
Step three: Copy the following code into the Upload button event.
protected void Btnupload_click (object sender, EventArgs e)
{
Stream imgstream = FUIMAGE.POSTEDFILE.INP Utstream;
int imglen = fuImage.PostedFile.ContentLength;
String imgname = Txtimagename.text;
byte[] Imgbinarydata = new Byte[imglen];
int n = imgstream.read (Imgbinarydata,0,imglen);
//use the web.config to store the connection string
SqlConnection connection = new SqlConnection (Configurat Ionmanager.
connectionstrings["ConnectionString"]. ConnectionString);
SqlCommand command = new SqlCommand (
INSERT into Image (imagename,image)
VALUES (@img_name, @img_d ATA) ", connection);
SqlParameter param0 = new SqlParameter (
"@img_name", SqlDbType.VarChar);
Param0. Value = imgname;
Command. Parameters.Add (PARAM0);
SqlParameter param1 = new SqlParameter (
"@img_data", sqldbtype.image);
param1. Value = Imgbinarydata;
Command. Parameters.Add (param1);
CoNnection. Open ();
int numrowsaffected = command. ExecuteNonQuery ();
Connection. Close ();
}