ASP.NET中将文件以二进制的形式保存到SQLServer数据库

开发网站时,经常需要网站中有上传文件的功能,上传文件的功能有两种:将文件名称保存到数据库,文件保存到服务器指定位置;将文件直接保存到数据库中

该方法介绍 将文件以二进制的形式保存到数据库中 (可以保存word文档,记事本文本,图片,压缩包……)

                 if (this.FileUpload1.PostedFile.FileName != "")
                  {
                    string ImgPath = FileUpload1.PostedFile.FileName;
                    string ImgName = ImgPath.Substring(ImgPath.LastIndexOf("\\") + 1);
                    string ImgExtend = ImgPath.Substring(ImgPath.LastIndexOf(".") + 1);
                    int FileLen = this.FileUpload1.PostedFile.ContentLength;
                    Byte[] FileData = new Byte[FileLen];
                    HttpPostedFile hp = FileUpload1.PostedFile;
                    Stream sr = hp.InputStream;
                    sr.Read(FileData, 0, FileLen);
                    SqlConnection con = new SqlConnection("server=.;user );
                    con.Open();
                    SqlCommand com = new SqlCommand("INSERT INTO tb_fileUp (name) VALUES (@imgdata)", con);
                    com.Parameters.Add("@imgdata", SqlDbType.Image);
                    com.Parameters["@imgdata"].Value = FileData;
                    com.ExecuteNonQuery();
                    this.LblMessage.Text = "保存成功!";
                }