首先在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]
向資料庫中存入圖檔:
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.IO;
using System.Data.SqlClient;
namespace UpLoadFile
{
/// <summary>
/// Summary description for UpLoadImage.
/// </summary>
public class UpLoadImage : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnUpload;
protected System.Web.UI.WebControls.Label txtMessage;
protected System.Web.UI.WebControls.TextBox txtDescription;
protected System.Web.UI.HtmlControls.HtmlTable Table1;
protected System.Web.UI.HtmlControls.HtmlInputFile UP_FILE;//HtmlControl、WebControls控件對象
protected Int32 FileLength = 0;
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.btnUpload.Click += new System.EventHandler(this.btnUpload_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnUpload_Click(object sender, System.EventArgs e)
{
HttpPostedFile UpFile = this.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("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
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();
}
}
}
}
将資料庫中的圖檔資料讀出來顯示:
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.IO;
using System.Data.SqlClient;
namespace UpLoadFile
{
/// <summary>
/// Summary description for ReadImage.
/// </summary>
public class ReadImage : System.Web.UI.Page
{
private void Page_Load(object sender, System.EventArgs e)
{
// Put user code to initialize the page here
if(!Page.IsPostBack)
{
string id = Request.QueryString["ImgID"]; //得到圖檔的ID
if (id != ""&& id != null && id != string.Empty)
{
ShowImage( id);
}
}
}
#region Web Form Designer generated code
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: This call is required by the ASP.NET Web Form Designer.
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
public void ShowImage(string id)
{
int ImgID = Convert.ToInt32(id); //ImgID為圖檔ID
//建立資料庫連結
SqlConnection Con = new SqlConnection("uid=sa;pwd= ;initial catalog=EE;data source=127.0.0.1;Connect Timeout=90");
String SqlCmd = "SELECT * FROM ImageStore WHERE ImageID = @ImageID";
SqlCommand CmdObj = new SqlCommand(SqlCmd, Con);
CmdObj.Parameters.Add("@ImageID", SqlDbType.Int).Value = ImgID;
try
{
Con.Open();
SqlDataReader SqlReader = CmdObj.ExecuteReader();
SqlReader.Read();
Response.ContentType = (string)SqlReader["ImageContentType"];//設定輸出檔案類型
//輸出圖象檔案二進制數制
Response.OutputStream.Write((byte[])SqlReader["ImageData"], 0, (int)SqlReader["ImageSize"]);
Response.End();
Con.Close();
}
catch
{
Response.Write("<script>alert('該圖檔不存在');</script>");
return;
}
}
}
}