现在的位置: 首页 > 综合 > 正文

存取显示Image类型的字段

2012年08月11日 ⁄ 综合 ⁄ 共 2338字 ⁄ 字号 评论关闭
using System;using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page
{
  Int32 FileLength = 0;
  protected void Page_Load(object sender, EventArgs e)
  {

  }

//存储

  protected void Button1_Click(object sender, EventArgs e)
  {
  HttpPostedFile UpFile = UP_File.PostedFile;//HttpPostedFile对象,用于读取图象文件属性  
  FileLength = UpFile.ContentLength;

  try
  {
  if (FileLength == 0)
  {
  lblMessage.Text = "<b>请选择您要上传的文件</b>";
  }
  else
  {
  Byte[] FileByteArray = new byte[FileLength]; //图象文件临时储存Byte数组  
  Stream StreamObj = UpFile.InputStream;//建立数据流对像  
  //读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度  
  StreamObj.Read(FileByteArray, 0, FileLength);

  SqlConnection Con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
  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 = UpFile.ContentType;//记录文件类型  
  //把其它单表数据记录上传  
  CmdObj.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200).Value = txtDescription.Text;
  //记录文件长度,读取时使用  
  CmdObj.Parameters.Add("@ImageSize", SqlDbType.BigInt, 8).Value = UpFile.ContentLength;
  Con.Open();
  CmdObj.ExecuteNonQuery();
  Con.Close();
  lblMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功  

  }
  }
  catch (Exception ex)
  {
  lblMessage.Text = ex.Message.ToString();
  }

  }

//读取

 private void ImgDataRead()
  {
  int ImgID = Convert.ToInt32(Request.QueryString["id"]);

  SqlConnection Con = new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);

  String SqlCmd = "SELECT * FROM ImageStore WHERE ID = @ImageID";
  SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
  CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
  Con.Open();
  SqlDataReader SqlReader = CmdObj.ExecuteReader();
  SqlReader.Read();
  Response.ContentType = (string)SqlReader["ImageContentType"];//设定输出文件类型  
  //输出图象文件二进制数制
   
  Response.OutputStream.Write((byte[])SqlReader["ImageData"],0,Convert.ToInt32(SqlReader["ImageSize"]));
  Response.BufferOutput = true;
  Con.Close();  

  }

}

抱歉!评论已关闭.