让图片以2进制的形式保存在数据库中

Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->       

int len = fu.PostedFile.ContentLength;  // 图片大小        

byte[] pic = new byte[len];  // 创建一个字节数组,大小为图片的大小,数据库中就存储这个东西        

fu.PostedFile.InputStream.Read(pic, 0, len); // 把上传控件中的文件用二进制读取存到pic字节数组中         //   插入图片到数据库中           

  SqlConnection connection = new         SqlConnection(@"server=.\sqlexpress;database=niunantest;uid=sa;pwd=123456");       

  try         {             connection.Open();             SqlCommand cmd = new SqlCommand("insert   into   picdata   "             + "([content])   values   (@pic)", connection);          

   cmd.Parameters.Add("@pic", pic);            

cmd.ExecuteNonQuery();           

  Label1.Text = "图片插入数据库成功!";

  Image1.ImageUrl = "getpic.ashx?t=" + DateTime.Now.Ticks;  // 显示刚刚插入数据库的图片         }      

   finally    

     {             connection.Close();         }

posted on 2013-03-19 12:12  平小  阅读(248)  评论(0编辑  收藏  举报