使用asp.net和C#如何存取Sql Server2000中的Image(16)类型的字段?

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.IO;
using System.Configuration;

namespace UploadImageToSqlserver
{
 ///


 ///上传图片到数据库存储
 ///

 public class UploadImage : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.Button Button1;
  protected System.Web.UI.WebControls.Label lblMessage;
  protected System.Web.UI.WebControls.TextBox txtDescription;
  protected System.Web.UI.HtmlControls.HtmlInputFile UP_File;
  protected System.Web.UI.WebControls.LinkButton LinkButton1;
  protected Int32 FileLength = 0;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  private void InitializeComponent()
  {   
   this.Button1.Click += new System.EventHandler(this.Button1_Click);
   this.LinkButton1.Click += new System.EventHandler(this.LinkButton1_Click);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  private void Button1_Click(object sender, System.EventArgs e)
  {
   HttpPostedFile UpFile = UP_File.PostedFile;//HttpPostedFile对象,用于读取图象文件属性
   FileLength = UpFile.ContentLength;
   try
   {
    if(FileLength == 0)
    {
     lblMessage.Text = "请选择您要上传的文件";
    }
    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  =  "

OK!你已经成功上传你的图片";//提示上传成功

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

  }

  private void LinkButton1_Click(object sender, System.EventArgs e)
  {
   Response.Redirect("ViewImage.aspx");
  }
 }
}

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using System.Drawing;

namespace UploadImageToSqlserver
{
 ///


 /// 从数据库中取出图片并显示在网页中。
 ///

 public class ViewImage : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DropDownList DdlImageId;
 
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   //建立数据库链接
   if(!IsPostBack)
   {
    BindDropDownList();
   }
 
  }
  private void BindDropDownList()
  {
   SqlConnection  Con  =  new  SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]);
   String  SqlCmd  =  "SELECT  ImageID  FROM  ImageStore"; 
   SqlDataAdapter  CmdObj  =  new  SqlDataAdapter(SqlCmd,  Con);
   DataSet ds = new DataSet();
   CmdObj.Fill(ds,"ImageId");

   DdlImageId.DataSource = ds.Tables["ImageId"].DefaultView;
   DdlImageId.DataTextField = "ImageID";
   DdlImageId.DataValueField = "ImageID";

   
   DdlImageId.DataBind();
   DdlImageId.Items.Insert(0, "请选择");
   DdlImageId.SelectedIndex = 0;

   Con.Close();
  }

  #region Web 窗体设计器生成的代码
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN: 该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  
  ///


  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  ///

  private void InitializeComponent()
  {   
   this.DdlImageId.SelectedIndexChanged += new System.EventHandler(this.DdlImageId_SelectedIndexChanged);
   this.Load += new System.EventHandler(this.Page_Load);

  }
  #endregion

  protected void DdlImageId_SelectedIndexChanged(object sender, System.EventArgs e)
  {
   int  ImgID  =  Convert.ToInt32(DdlImageId.SelectedValue);
   SqlConnection  Con  =  new  SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["ConnectionString"]); 
   String  SqlCmd  =  "SELECT  *  FROM  ImageStore  WHERE  ImageID  =  @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,  (int)SqlReader["ImageSize"]);
   Response.BufferOutput = true; 
   Con.Close();

  
 

  }
 }
}

 

另外 “孟子E章”处理如下:

下面的代码实现从SQL Server数据库提取图片并显示在DataGrid的功能。下面的代码实现从SQL Server数据库提取图片并显示在DataGrid的功能。

DataGridShowImage.aspx

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >
<HTML>
<HEAD>
  <title>从数据库中取得照片并显示在DataGrid中</title>
  <meta name="GENERATOR" Content="Microsoft Visual Studio 7.0">
  <meta name="CODE_LANGUAGE" Content="C#">
  <meta name="vs_defaultClientScript" content="JavaScript">
  <meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form id="DataGridShowImage" method="post" runat="server">
  <h4 align="center">从数据库中取得照片并显示在DataGrid中</h4>
  <asp:DataGrid ID="DG_Persons" AutoGenerateColumns="False" Width="99%" HeaderStyle-BackColor="#ff0000"
   HeaderStyle-Font-Bold="True" HeaderStyle-ForeColor="#ffffff" ItemStyle-BackColor="Beige"
    BorderColor="#000000" Runat="server" HeaderStyle-HorizontalAlign="Center">
  <Columns>
    <asp:TemplateColumn HeaderText="姓名">
      <ItemTemplate>
        <asp:Label Runat="server" Text='' ID="Label1"/>
      </ItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="电子邮件">
      <ItemTemplate>
        <asp:Label Runat="server" Text='' ID="Label2"/>
      </ItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="性别">
      <ItemTemplate>
        <asp:Label Runat="server" Text='' ID="Label3"/>
      </ItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="出生日期">
      <ItemTemplate>
        <asp:Label Runat="server" Text='' ID="Label4"/>
      </ItemTemplate>
    </asp:TemplateColumn>
    <asp:TemplateColumn HeaderText="照片">
      <ItemTemplate>
        <asp:Image Runat=server ID="Image1"
         ImageUrl='' />
      </ItemTemplate>
    </asp:TemplateColumn>
  </Columns>
  </asp:DataGrid>
</form>
</body>
</HTML>
?
?
DataGridShowImage.aspx.cs
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;

namespace eMeng.Exam.DataGridShowImage
{
 /// <summary>
 /// DataGridShowImage 的摘要说明。
 /// </summary>
 public class DataGridShowImage : System.Web.UI.Page
 {
  protected System.Web.UI.WebControls.DataGrid DG_Persons;

  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   if(!this.IsPostBack)
   {
    BindGrid();
   }

  }
  private void BindGrid()
  {
   string strCnn  = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;";
   SqlConnection myConnection = new SqlConnection(strCnn);
   SqlCommand myCommand = new SqlCommand("SELECT * FROM Person", myConnection);
   myCommand.CommandType = CommandType.Text;
   try
   {
    myConnection.Open();
    DG_Persons.DataSource = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    DG_Persons.DataBind();
   }
   catch(SqlException SQLexc)
   {
    Response.Write("提取数据时出现错误:" + SQLexc.ToString());
   }
  }
  protected string FormatURL(object strArgument)
  {
   return "ReadImage.aspx?id=" + strArgument.ToString();
  }

#region Web Form Designer generated code
  override protected void OnInit(EventArgs e)
  {
   //
   // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
   //
   InitializeComponent();
   base.OnInit(e);
  }
  /// <summary>
  /// 设计器支持所需的方法 - 不要使用代码编辑器修改
  /// 此方法的内容。
  /// </summary>
  private void InitializeComponent()
  {    
   this.Load += new System.EventHandler(this.Page_Load);
  }
#endregion
 }
}
ReadImage.aspx
?
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Web;
using System.Data.SqlClient;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace eMeng.Exam.DataGridShowImage
{
  /// <summary>
  /// ReadImage 的摘要说明。
  /// </summary>
  public class ReadImage : System.Web.UI.Page
  {
  private void Page_Load(object sender, System.EventArgs e)
  {
   // 在此处放置用户代码以初始化页面
   string strImageID = Request.QueryString["id"];
   SqlConnection myConnection = new SqlConnection("Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;");
   SqlCommand myCommand = new SqlCommand("Select PersonImageType, PersonImage from Person Where PersonID=" 
    + strImageID, myConnection);

   try
   {
    myConnection.Open();
    SqlDataReader myDataReader;
    myDataReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
    if(myDataReader.Read())
    {
     Response.Clear();

     Response.ContentType = myDataReader["PersonImageType"].ToString();
     Response.BinaryWrite((byte[])myDataReader["PersonImage"]);
    }
    myConnection.Close();
   }
   catch (SqlException SQLexc)
   {
   }
   Response.End();
  }
    #region Web Form Designer generated code
    override protected void OnInit(EventArgs e)
    {
      //
      // CODEGEN:该调用是 ASP.NET Web 窗体设计器所必需的。
      //
      InitializeComponent();
      base.OnInit(e);
    }
		
    /// <summary>
    /// 设计器支持所需的方法 - 不要使用代码编辑器修改
    /// 此方法的内容。
    /// </summary>
    private void InitializeComponent()
    {    
      this.Load += new System.EventHandler(this.Page_Load);
    }
    #endregion
  }
}

下面的代码实现向SQL Server数据库添加图片和文字的功能。

首先,在SQL查询分析器中执行下面的语句,以创建表和存储过程。

Drop Table Person

Go
Create Table Person
(
PersonID Int Identity,
PersonEmail Varchar(255),
PersonName Varchar(255),
PersonSex Char(1),
PersonDOB DateTime,
PersonImage Image,
PersonImageType Varchar(255)
)

Drop Proc sp_person_isp

Go
Create Proc sp_person_isp
@PersonEmail Varchar(255),
@PersonName Varchar(255),
@PersonSex Char(1),
@PersonDOB DateTime,
@PersonImage Image,
@PersonImageType Varchar(255)
As
Begin
  Insert into Person 
   (PersonEmail, PersonName, PersonSex, 
   PersonDOB, PersonImage, PersonImageType)
   Values
   (@PersonEmail, @PersonName, @PersonSex, 
   @PersonDOB, @PersonImage, @PersonImageType)
End

Go



<HTML>
<HEAD>
<title>向SQL Server插入图片</title>
<script runat="server">
Public Sub AddPerson(sender As Object, e As EventArgs)
  Dim intImageSize As Int64
  Dim strImageType As String
  Dim ImageStream As Stream
  ' 获得图片的大小
  intImageSize = PersonImage.PostedFile.ContentLength
  ' 获得图片类型
  strImageType = PersonImage.PostedFile.ContentType
  '读取图片
  ImageStream = PersonImage.PostedFile.InputStream
  Dim ImageContent(intImageSize) As Byte
  Dim intStatus As Integer
  intStatus = ImageStream.Read(ImageContent, 0, intImageSize)
  ' 创建Connection和Command对象
  Dim strCnn As String = "Data Source=.;Initial Catalog=mxh;User Id=sa;Password=;"
  Dim myConnection As New SqlConnection(strCnn)
  Dim myCommand As New SqlCommand("sp_person_isp", myConnection)
  ' 使用存储过程
  myCommand.CommandType = CommandType.StoredProcedure
  ' 向存储过程添加参数
  Dim prmEmail As New SqlParameter("@PersonEmail", SqlDbType.VarChar, 255)
  prmEmail.Value = txtPersonEmail.Text
  myCommand.Parameters.Add(prmEmail)

  Dim prmName As New SqlParameter("@PersonName", SqlDbType.VarChar, 255)
  prmName.Value = txtPersonName.Text
  myCommand.Parameters.Add(prmName)
  Dim prmSex As New SqlParameter("@PersonSex", SqlDbType.Char, 1)

  If sexMale.Checked Then
	  prmSex.Value = "M"
  Else
	  prmSex.Value = "F"
  End If
  myCommand.Parameters.Add(prmSex)
  
  Dim prmPersonDOB As New SqlParameter("@PersonDOB", SqlDbType.DateTime)
  prmPersonDOB.Value = txtPersonDob.Text
  myCommand.Parameters.Add(prmPersonDOB)

  Dim prmPersonImage As New SqlParameter("@PersonImage", SqlDbType.Image)
  prmPersonImage.Value = ImageContent
  myCommand.Parameters.Add(prmPersonImage)

  Dim prmPersonImageType As New SqlParameter("@PersonImageType", SqlDbType.VarChar, 255)
  prmPersonImageType.Value = strImageType
  myCommand.Parameters.Add(prmPersonImageType)

  Try
	  myConnection.Open()
	  myCommand.ExecuteNonQuery()
	  myConnection.Close()
	  Response.Write("添加成功!")
    Catch SQLexc As SqlException
    Response.Write("添加失败,原因:" & SQLexc.ToString())
  End Try
End Sub
</script>
</HEAD>
<body style="FONT: 9pt 宋体">
    <form enctype="multipart/form-data" runat="server" ID="Form1">
      <asp:Table Runat="server" Width="50%" BorderWidth="1" BackColor="Beige" ID="Table1"
	 Font-Name="宋体" Font-Size="9pt">
        <asp:TableRow>
          <asp:TableCell ColumnSpan="2" BackColor="#ff0000">
            <asp:Label ForeColor="#ffffff" font-bold="True" Runat="server" Text="添加新用户" ID="Label1" />
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell HorizontalAlign="Right">
            <asp:Label Runat="server" Text="姓名" ID="Label2" />
          </asp:TableCell>
          <asp:TableCell>
            <asp:TextBox id="txtPersonName" Runat="server" />
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell HorizontalAlign="Right">
            <asp:Label Runat="server" Text="电子邮件" ID="Label3" />
          </asp:TableCell>
          <asp:TableCell>
            <asp:TextBox id="txtPersonEmail" Runat="server" />
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell HorizontalAlign="Right">
            <asp:Label Runat="server" Text="性别" ID="Label4"/>
          </asp:TableCell>
          <asp:TableCell>
            <asp:RadioButton GroupName="sex"  Text="男" ID="sexMale" Runat="server" />
            <asp:RadioButton GroupName="sex"  Text="女" ID="sexFeMale" Runat="server" />
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell HorizontalAlign="Right">
            <asp:Label Runat="server" Text="出生日期" ID="Label5"/>
          </asp:TableCell>
          <asp:TableCell>
            <asp:TextBox id="txtPersonDOB" Runat="server" />
          </asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell HorizontalAlign="Right">
            <asp:Label Runat="server" Text="照片" ID="Label6"/>
          </asp:TableCell>
          <asp:TableCell>
            <input type="file" id="PersonImage" runat="server" NAME="PersonImage" /></asp:TableCell>
        </asp:TableRow>
        <asp:TableRow>
          <asp:TableCell ColumnSpan="2" HorizontalAlign="Center">
            <asp:Button Text=" 添  加 " OnClick="AddPerson" Runat="server" ID="Button1"/>
          </asp:TableCell>
        </asp:TableRow>
      </asp:Table>
    </form>
</body>
</HTML>
暂无C#版本!
ReadImage.aspx.cs
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值