SAL

  博客园  :: 首页  :: 新随笔  :: 订阅 订阅  :: 管理

ASP.NET图片保存/取出SQL数据库

Posted on 2006-12-09 16:25  SAL  阅读(2033)  评论(2编辑  收藏  举报
摘要
.NET是由微软开发的一种新型的分布式计算平台,ASP.NET是它针对Web开发的编程模式。本文的目的是在开发数据驱动的ASP.NET Web应用程序中获取一些好的经验。这个应用程序将告诉你怎么把一幅图片保存到数据库中以及怎样把图片从数据库中读取出来。它以ADO.NET作为数据访问机制,C#作为编程语言,SQL 2000/2005 Server作为后台数据库。
概述
一般的,很大的图片文件往往被保存在Web服务器的文件夹中,而不是数据库中。在一些实例中,以银行系统为例,人们先把用户的签名做成图片文件,然后保存到数据库中。
数据库模式

在这个示范中,微软的SQL 2000/2005 Server被用作后台数据库。我使用了一种比较特殊的数据类型 image 。这 image 数据类型是被用来保存图片到数据库的。
所使用的控件:
System.Web.UI.HtmlControls.HtmlInputFile
System.Web.UI.WebControls.TextBox
System.Web.UI.WebControls.Button

所使用的名字空间: 
       using System.Data.SqlClient;
       using System.Drawing;
       using System.Data;
       using System.IO;
       using System.Drawing.Imaging;

编码
使用 HtmlInputFile 类,它可以用 <input type="file" runat ="server"/> 标签来声明一个实例。下面的例子是一个完整的 ASPX 文件,它让用户上传图片文件以及图片的说明。OnUpload 方法把图片以及说明写到iSense 数据库的Picture 表中。

// 保存图片文件到数据库的源码
public void OnUpload(Object sender, EventArgs e)
{
// 从输入文件中创建一个 byte[]       注:在此之前可写代码控制图片上传的格式!
    int len = Upload.PostedFile.ContentLength;
    byte[] pic = new byte[len];
    Upload.PostedFile.InputStream.Read (pic, 0, len);

// 插入图片和说明到数据库中
SqlConnection connection = new 
     SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
    try
    {
        connection.Open ();
        SqlCommand cmd = new SqlCommand ("insert into Image " 
          + "(Picture, Comment) values (@pic, @text)", connection);
        cmd.Parameters.Add ("@pic", pic);
        cmd.Parameters.Add ("@text", Comment.Text);
        cmd.ExecuteNonQuery ();
    }
    finally 
    {
        connection.Close ();
    }
}
上面创建的函数可以通过使用按钮的 onClick 属性来调用。
如何使用ADO.NET技术从数据库中读取图片并把它显示在Web页面上?
这里,我使用Web页面来显示图片,而没有用其他任何控件。下面的代码是用来显示数据库中的图片。

private void Page_Load(object sender, System.EventArgs e)
{
    MemoryStream stream = new MemoryStream ();
    SqlConnection connection = new 
      SqlConnection (@"server=INDIA\INDIA;database=iSense;uid=sa;pwd=india");
    try
    {
        connection.Open ();
        SqlCommand command = new 
        SqlCommand ("select Picture from Image where id="+Request["id"], connection);
        byte[] image = (byte[]) command.ExecuteScalar ();   
        stream.Write (image, 0, image.Length);
        Bitmap bitmap = new Bitmap (stream);
        Response.ContentType = "image/gif";
        bitmap.Save (Response.OutputStream, ImageFormat.Gif);
      } 
    catch
        {
            string strblandImagePath = Server.MapPath("");
            strblandImagePath += "NoImg.gif";     
            FileStream FileBlandImagestream = File.OpenRead(strblandImagePath);
            Bitmap bitImage = new Bitmap(FileBlandImagestream);
            Response.ContentType = "image/gif";
            bitImage.Save(Response.OutputStream, ImageFormat.Gif);
        }
    finally
    {
        connection.Close ();
        stream.Close ();
    }
}