SQL Server Database Code
<%@ Page language=" c#" enableviewstate="true" %> <%@ Import namespace=" system.data.sqlclient" %> <! DOCTYPE HTML Public "-//W3C//DTD XHTML 1.0 transitional//en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server"> String strcnn = " Persist Security Info=false; User Id=sa; Password=;initial Catalog=book; server= (local);"; protected void Button1_Click (object sender, EventArgs e) {System.IO.Stream Filedatastream = FileUpload1.PostedFile.Inpu Tstream; if (filedatastream.length < 1) {msg.text = " Please select file. "; Return //Get file size int filelength = FileUpload1.PostedFile.ContentLength; Create array byte[] Filedata = new Byte[filelength]; Populate the file stream to the array filedatastream.read (filedata, 0, filelength); Get file type string fileType = FileUpload1.PostedFile.ContentType; Build database connections, SQL statements, createConstruction parameter SqlConnection myconnection = new SqlConnection (STRCNN); SqlCommand command = new SqlCommand ("insert into Userphoto (username,contenttype,photo) " + " VALUES (@UserName, @ContentType, @Photo) ", MyConnection); Command. Parameters.addwithvalue (" @UserName ", TextBox1.Text); Command. Parameters.addwithvalue (" @ContentType ", FileType); Command. Parameters.addwithvalue (" @Photo ", filedata); Open the connection, execute the query Myconnection.open (); Command. ExecuteNonQuery (); Myconnection.close (); Response.Redirect (Request.rawurl); } protected void Page_Load (object sender, EventArgs e) {if (! Page.IsPostBack) {Bindgrid ();}} private void Bindgrid () {SqlConnection myconnection = new SqlConnection (STRCNN); SqlCommand mycommand = new SqlCommand (" SELECT * from Userphoto order by ID Desc", myconnection); try {myconnection.open (); Gridview1.datasource = Mycommand.executereader (System.Data.CommandBehavior.CloseConnectiON); Gridview1.databind (); The catch (Exception Sqlexc) {Response.Write (" error when extracting data:" + sqlexc.tostring ());} Protected string FormatUrl (object strargument) {return " readimage.aspx?id=" + strargument.tostring (); } </script> <html xmlns="http://www.w3.org/1999/xhtml"> <head id=" head1" Runat="server"> <title> uploading files to database </title> </head> <body> <form id=" mengxianhui" Runat="server"> <asp:gridview id=" gridview1" runat="server" Autogeneratecolumns="false"> < Columns> <asp:TemplateField> <ItemTemplate> <% #Eval (" username")%> </ItemTemplate> </asp:TemplateField> <asp:templatefield> <ItemTemplate> <img src="<% #FormatURL (Eval ("id"))%>"/>&lt ;/itemtemplate> </asp:TemplateField> </Columns> </asp:GridView> <BR/> <BR/> Name: <asp:textbox id=" textbox1" Runat="server"></asp:textbox> <BR/> Photo: <asp:fileupload id=" fileupload1" runat="server" /> <asp:button id="btnupload" runat="server" text=" Upload " onclick=" Button1_click"></asp:button> <p> <asp:label id=" msg" runat="server" forecolor=" Red"></asp:label></p> </form> </body> </html>