<input type=file > 对象
PostedFile | HttpPostedFile 对象 |
InputStream | Stream 对象 |
ContentLength | 文件长度 |
ContentType | 文件类型,例:"image/pjpeg" |
SaveAs( filename ) | 上传文件存入到磁盘 |
Read(char [] buff, int offset, int count) | 把上传文件内容读入到 char 数组 |
代码 | protected void Submit1_ServerClick(object sender, EventArgs e) { System.IO.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 = ConfigurationManager.ConnectionStrings["connstr"].ConnectionString; SqlConnection connection = new SqlConnection(connstr); SqlCommand command=new SqlCommand("INSERT INTO IMG (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(); } |
表结构 | create table IMG ( id integer identity(1,1) , imgtitle varchar(50), imgtype varchar(50), imgdata image ) |
表单 | <form id="form1" runat="server" enctype="multipart/form-data"
method="post"> <div> 这是一个 ASP.NET 测试应用程序。 <br /> 上传图象:<input id="File1" type="file" runat="server" /> <br /> 图象标题:<asp:TextBox ID="TextBox1" runat="server" Width="221px"></asp:TextBox><br /> <input id="Submit1" type="submit" value="submit" onclick="return Submit1_onclick()" onserverclick="Submit1_ServerClick" runat="server" /></div> </form> |