ASP.NET存取图片到数据库

private void btnUpload_Click(object sender, System.EventArgs e)
{
 //得到用户要上传的文件名
 string strFilePathName = loFile.PostedFile.FileName;
 string strFileName = Path.GetFileName(strFilePathName);
 int FileLength = loFile.PostedFile.ContentLength;
 if(FileLength<=0)
  return;
 try
 {//上传文件
  Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组
  Stream StreamObject = loFile.PostedFile.InputStream; //建立数据流对像
  //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度
  StreamObject.Read(FileByteArray,0,FileLength);
  //建立SQL Server链接
  string strCon = System.Configuration.ConfigurationSettings.AppSettings["DSN"];
  SqlConnection Con = new SqlConnection(strCon);
  String SqlCmd = "INSERT INTO ImageStore (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@Image, @ContentType, @ImageDescription, @ImageSize)";
  SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
  CmdObj.Parameters.Add("@Image",SqlDbType.Binary, FileLength).Value = FileByteArray;
  CmdObj.Parameters.Add("@ContentType", SqlDbType.VarChar,50).Value = loFile.PostedFile.ContentType; //记录文件类型
  //把其它单表数据记录上传
  CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar,200).Value = tbDescription.Text;
  //记录文件长度,读取时使用
  CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt,8).Value = FileLength;
  Con.Open();
  CmdObj.ExecuteNonQuery();
  Con.Close();
  //跳转页面
  Response.Redirect("ShowAll.aspx");
 }
 catch
 {
 }
}
posted @ 2006-07-10 11:53  pensir  阅读(326)  评论(0编辑  收藏  举报