把图片保存到SQL中并显示出来
CREATE TABLE [imageinsertsql] ( [Imageid] [int] IDENTITY (1, 1) NOT NULL , [imagetitle] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [imagetype] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL , [imagesize] [int] NULL , [imagedata] [image] NULL ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY] GO <div> <asp:Label ID="Label1" runat="server" Height="43px" Text="Label" Width="360px"></asp:Label><br /> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br /> <input id="File1" type="file" runat="server"/><br /> <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" /> <br /> <asp:TextBox ID="TextBox2" runat="server">0</asp:TextBox><br /> <asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="显示图片" /> </div> protected void Button1_Click(object sender, EventArgs e) { HttpPostedFile UpFile = File1.PostedFile; int FileLenght = UpFile.ContentLength; TextBox1.Text = FileLenght.ToString(); try { if (FileLenght == 0) { TextBox1.Text = "<b>你未选择上传得文件</b>"; } else { Byte[] FileByteArray= new Byte[FileLenght]; Stream StreamObject =UpFile.InputStream; StreamObject.Read(FileByteArray,0,FileLenght); string strconn="Server=.;UID=sa;PWD=;Database=Demo"; string strinsert="insert into imageinsertsql(imagetitle,imagesize,imagetype,imagedata) values("; strinsert+="@imagetitle,@imagesize,@imagetype,@imagedata)"; SqlCommand mycomm = new SqlCommand(strinsert, new SqlConnection(strconn)); mycomm.Parameters.Add("@imagetitle", SqlDbType.Text); mycomm.Parameters.Add("@imagesize", SqlDbType.Int); mycomm.Parameters.Add("@imagetype", SqlDbType.Text); mycomm.Parameters.Add("@imagedata", SqlDbType.Image); mycomm.Parameters["@imagetitle"].Value = TextBox1.Text; mycomm.Parameters["@imagesize"].Value = FileLenght; mycomm.Parameters["@imagetype"].Value = UpFile.ContentType; mycomm.Parameters["@imagedata"].Value = FileByteArray; mycomm.Connection.Open(); mycomm.ExecuteNonQuery(); mycomm.Connection.Close(); Label1.Text = "<B>上传文件成功</B>"; } } catch(Exception ex) { TextBox1.Text = ex.Message.ToString(); } } protected void Button2_Click(object sender, EventArgs e) { int imageid = Convert.ToInt32(TextBox2.Text); string strconn = "Server=.;UID=sa;PWD=;Database=Demo"; string strsquery = "select * from imageinsertsql where imageid=@imageid"; SqlCommand mycom = new SqlCommand(strsquery, new SqlConnection(strconn)); mycom.Parameters.Add("@imageid", SqlDbType.Int); mycom.Parameters["@imageid"].Value = imageid; mycom.Connection.Open(); SqlDataReader dr = mycom.ExecuteReader(); if (dr.Read()) { Response.ContentType = (string)dr["imagetype"]; Response.OutputStream.Write((byte[])dr["imagedata"], 0, (int)dr["imagesize"]); } else { Response.Write("没有这个ID"); Response.End(); } }