将图像保存到 SQL Server 2000 数据库






4.56/5 (83投票s)
如何在 ASP.NET 中将文件上传到网页? 如何使用 ADO.NET 从数据库读取图像并在网页中显示它?
摘要
.NET 是微软开发的新分布式计算平台,ASP.NET 是其用于 Web 开发的编程模型。 本文旨在通过实际应用程序获得开发数据驱动的 ASP.NET Web Forms 应用程序的良好体验。 此应用程序将教你如何将图像文件保存到数据库中,以及如何从数据库中检索它。 它使用 ADO.NET 作为数据访问机制,C# 作为开发语言,SQL Server 2000 作为后端数据库。
解决方案概述
通常,图像保存在 Web 服务器文件夹中,而不是在数据库中; 这是针对较大的文件大小类别。 在某些情况下,例如银行,他们扫描用户签名作为图像文件并将该文件保存到数据库中。
- 数据库架构
MS SQL Server 2000 用作此小型演示的后端数据库。 我在 SQL Server 中使用了一种特殊的数据类型,称为
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
方法将图像和注释写入名为 Pictures 的表中,该表位于名为 iSense 的 SQL Server 数据库中。
// Source Code for Save the image file into the database
public void OnUpload(Object sender, EventArgs e)
{
// Create a byte[] from the input file
int len = Upload.PostedFile.ContentLength;
byte[] pic = new byte[len];
Upload.PostedFile.InputStream.Read (pic, 0, len);
// Insert the image and comment into the database
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 从数据库读取图像并在网页中显示它?
在这里,我使用网页来显示图像,而不是任何其他控件。 以下是从数据库显示图像的代码。
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
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", 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);
}
finally
{
connection.Close ();
stream.Close ();
}
}
GDI+ 函数提供了一组丰富的功能,用于管理和修改图像数据。 本文的示例仅提供了你可以使用 System.Drawing
和 System.Drawing.Imaging
命名空间中提供的类来利用的功能的一瞥。 例如,你可以开发用于在 Web 上存储和管理图像文件的应用程序,或者你可以提供一个简单、易于部署的应用程序,使用户能够操作图像。
如何运行此应用程序? 首先,创建一个虚拟目录并将项目文件放入虚拟目录中。 然后更改以下语句中的服务器名称、数据库名称和表名。
SqlConnection connection = new SqlConnection
("server=localhost;database=mypictures;uid=sa;pwd=");
并发布该项目以获得最佳结果。