asp.net c#读取sql server 图像字段

来源:互联网 发布:it云端 编辑:程序博客网 时间:2024/04/30 03:41
 

在ASP中,我们用Request.TotalBytes、Request.BinaryRead()来上传图片,这个可恶的BinaryRead()方法非常笨,单个文件上传倒没什么大事,单如果多个图片上专可就花大气力了…!而现在ASP.Net中将会把解决以前ASP中文件上传的种种问题,使你在ASP.Net中轻轻松松开发出功能强大的上传程序...

首先在SQL Server中建立一个图片存储的数库表,ImageData Column为图象二进制数据储存字段,ImageContentType Column为图象文件类型记录字段,ImageDescription Column为储蓄图象文件说明字段,ImageSize Column为储存图象文件长度字段,结构如下:

CREATE TABLE [dbo].[ImageStore] (

[ImageID] [int] IDENTITY (1, 1) NOT NULL ,

[ImageData] [image] NULL ,

[ImageContentType] [varchar] (50) COLLATE Chinese_PRC_CI_AS NULL ,

[ImageDescription] [varchar] (200) COLLATE Chinese_PRC_CI_AS NULL ,

[ImageSize] [int] NULL

) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

//UploadImage.aspx文件

<%@ Page language="c#" Codebehind="UpLoadImage.aspx.cs" AutoEventWireup="false" Inherits="UploadImage.UploadImage" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" >

<HTML>

<title>上传图片</title>

<BODY bgcolor="#ffffff">

<FORM ENCTYPE="multipart/form-data" RUNAT="server" ID="Form1">

<TABLE RUNAT="server" WIDTH="700" ALIGN="left" ID="Table1" cellpadding="0" cellspacing="0"

border="0">

<TR>

<TD>上传图片(选择你要上传的图片)</TD>

<TD>

<INPUT TYPE="file" ID="UP_FILE" RUNAT="server" STYLE="WIDTH:320px" ACCEPT="text/*" NAME="UP_FILE">

</TD>

</TR>

<TR>

<TD>

文件说明(添加上传图片说明,如:作者、出处)

</TD>

<TD>

<asp:TextBox RUNAT="server" WIDTH="239" ID="txtDescription" MAINTAINSTATE="false" />

</TD>

</TR>

<TR>

<TD>

<asp:Label RUNAT="server" ID="txtMessage" FORECOLOR="red" MAINTAINSTATE="false" />

</TD>

<TD>

<asp:Button RUNAT="server" WIDTH="239" ONCLICK="Button_Submit" TEXT="Upload Image" ID="Button1" />

</TD>

</TR>

</TABLE>

</FORM>

</BODY>

</HTML>

// //UploadImage.aspx.cs文件

using System;

using System.Web;

using System.IO;

using System.Data;

using System.Data.SqlClient;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.HtmlControls;

namespace UploadImage

{

public class UploadImage : Page

{

protected HtmlInputFile UP_FILE; //HtmlControl、WebControls控件对象

protected TextBox txtDescription;

protected Label txtMessage;

protected System.Web.UI.WebControls.Button Button1;

protected Int32 FileLength = 0;

private void InitializeComponent()

{

this.Button1.Click += new System.EventHandler(this.Button_Submit);

this.Load += new System.EventHandler(this.Page_Load);

}

//记录文件长度变量

protected void Button_Submit(System.Object sender, System.EventArgs e)

{

HttpPostedFile UpFile = UP_FILE.PostedFile; //HttpPostedFile对象,用于读取图象文件属性

FileLength = UpFile.ContentLength; //记录文件长度

try

{

if (FileLength == 0)

{

txtMessage.Text = "<b>请你选择你要上传的文件</b>"; //文件长度为零时

}

else

{

Byte[] FileByteArray = new Byte[FileLength]; //图象文件临时储存Byte数组

Stream StreamObject = UpFile.InputStream; //建立数据流对像

//读取图象文件数据,FileByteArray为数据储存体,0为数据指针位置、FileLnegth为数据长度

StreamObject.Read(FileByteArray,0,FileLength);

//建立SQL Server链接

SqlConnection Con = new SqlConnection("Data Source=Localhost;Initial Catalog=testdb;User ID=sa;Pwd=;");

//存入数据库

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();

txtMessage.Text = "<p><b>OK!你已经成功上传你的图片</b>";//提示上传成功

}

}

catch (Exception ex)

{

txtMessage.Text = ex.Message.ToString();

}}

private void Page_Load(object sender, System.EventArgs e)

{

}}

}

//ReadImage.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 WebApplication1

{

/// <summary>

/// ReadImage 的摘要说明。

/// </summary>

public class ReadImage : System.Web.UI.Page

{

private void Page_Load(object sender, System.EventArgs e)

{

int ImgID = Convert.ToInt32(Request.QueryString["ImgID"]); //ImgID为图片ID

//建立数据库链接

SqlConnection Con = new SqlConnection("Data Source=.;Initial Catalog=testdb;User ID=sa;Pwd=;");

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.bOutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);

//     while(SqlReader.Read())

//     {

//      Response.BinaryWrite(SqlReader.Item["ImageData"])

//

//     }

Response.End();

Con.Close();

//很简单吧^_^

// 在此处放置用户代码以初始化页面

}

#region Web 窗体设计器生成的代码

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

}

}

//showImage.htm

<html>

<body>

这个是从数据库读取出来的图象:<img src="ReadImage.aspx?ImgID=1">

<body>

</html>

HttpPostedFile 类

提供访问客户端已经上载的各个文件的方法。

备注

HttpFileCollection 类提供对作为文件集合从客户端上载的所有文件的访问。HttpPostedFile 提供属性和方法以获取关于个别文件的信息以及读取和保存文件。文件以 MIME 多部分/窗体数据格式上载,并且缓存在服务器内存中,直到显式保存到磁盘上。

HtmlInputFile 控件可用于选择文件和从客户端上载文件。

在 machine.config 或 Web.config 配置文件的 <httpRuntime> 元素元素的 maxRequestLength 属性中,可指定允许上载文件大小的最大值。默认值为 4 兆字节。

以下示例为 ASP.NET 应用程序指定 HTTP 运行时参数。

<configuration>     <system.web>        <httpRuntime maxRequestLength="4000"           useFullyQualifiedRedirectUrl="true"           executionTimeout="45"           versionHeader="1.1.4128"/>     </system.web></configuration>