保存圖片到數(shù)據(jù)庫 收藏
以下的例子是如何將圖片保存到數(shù)據(jù)庫,所用的Northwind數(shù)據(jù)庫,在里面建了一張
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[UpImage]') and OBJECTPROPERTY(id, N'IsUserTable') = 1)
drop table [dbo].[UpImage]
GO
后臺代碼: 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 NetTest
{
/// <summary>
/// UpImageToDataBase 的摘要說明。
/// </summary>
public class UpImageToDataBase : System.Web.UI.Page
{
protected System.Web.UI.WebControls.Button btnSubmit;
protected System.Web.UI.HtmlControls.HtmlInputFile myFile;
private Int32 FileLength=0;//有可能圖片的大小會超出INT的范圍,所以聲明為Int32,當(dāng)然這和下面大小的判斷有關(guān)系
private string con="server=localhost;uid=sa;pwd=;database=northwind";
private void Page_Load(object sender, System.EventArgs e)
{
// 在此處放置用戶代碼以初始化頁面
}
#region Web 窗體設(shè)計器生成的代碼
override protected void OnInit(EventArgs e)
{
//
// CODEGEN: 該調(diào)用是 ASP.NET Web 窗體設(shè)計器所必需的。
//
InitializeComponent();
base.OnInit(e);
}
/// <summary>
/// 設(shè)計器支持所需的方法 - 不要使用代碼編輯器修改
/// 此方法的內(nèi)容。
/// </summary>
private void InitializeComponent()
{
this.btnSubmit.Click += new System.EventHandler(this.btnSubmit_Click);
this.Load += new System.EventHandler(this.Page_Load);
}
#endregion
private void btnSubmit_Click(object sender, System.EventArgs e)
{
try
{
SqlConnection conn = new SqlConnection(con);
string FileName=myFile.Value;
HttpPostedFile UpFile=myFile.PostedFile;//獲取對由客戶端指定的上傳文件的訪問
FileLength=UpFile.ContentLength;//獲取上傳文件的字節(jié)大小
if(FileLength==0)
{
Response.Write("<script>alert('對不起,請選擇要上傳的圖片')</script>");
return;
}
string exName=FileName.Substring(FileName.LastIndexOf(".")+1).ToUpper();//截取圖片的后綴名
if(exName=="JPG"||exName=="BMP"||exName=="GIF")//判斷圖片的類型
{
if(FileLength>204800)//判斷圖片是否大于200k(根據(jù)自己的需要判斷大?。?br> {
Response.Write("<script>alert('對不起,圖片大小不能大于200K')</script>");
return;
}
else
{
string ImageName=DateTime.Now.ToString("yyyyMMddhhmmssfff")+"."+exName;//圖片名稱設(shè)置為保存的時間
Byte[] FileByte = new Byte[FileLength]; //圖象文件儲存到數(shù)組
Stream ObjectStream = UpFile.InputStream;//建立數(shù)據(jù)流對像,獲取一個 Stream 對象,該對象指向一個上載文件,以準(zhǔn)備讀取該文件的內(nèi)容。
ObjectStream.Read(FileByte,0,FileLength); //讀取圖象文件數(shù)據(jù)
string StrSql="Insert Into UpImage Values(@ImageName,@Image)";
SqlCommand Cmd=new SqlCommand(StrSql,conn);
Cmd.Parameters.Add("@Image",SqlDbType.Binary,FileLength).Value=FileByte;
Cmd.Parameters.Add("@ImageName",SqlDbType.VarChar,100).Value=ImageName;
conn.Open();
Cmd.ExecuteNonQuery();
conn.Close();
Response.Write("<script>alert('圖片保存到數(shù)據(jù)庫成功')</script>");
}
}
else
{
Response.Write("<script>alert('對不起,請選擇正確的的圖片')</script>");
return;
}
}
catch(Exception ex)
{
Response.Write("<script>alert('"+ex.Message+"')</script>");
}
}
}
}
如果要將圖片顯示在頁面上,可以用一下的代碼:在頁面上加一個BUTTON控件,在CLICK事件中加入一下代碼即可
SqlConnection cn=new SqlConnection(conn);
SqlCommand cmd=new SqlCommand();
cmd.CommandText="select Image from UpImage";
cmd.Connection=cn;
cn.Open();
this.Response.ContentType="image/jpeg";
//this.Response.ContentType="image/bmp";
//this.Response.ContentType="image/gif";
SqlDataReader dr=cmd.ExecuteReader();
while(dr.Read())
{
this.Response.BinaryWrite((byte[])dr["Image"]);
}
cn.Close();
以上代碼只能在頁面上顯示一張圖片,因?yàn)橛玫氖荝esponse.BinaryWrite(),所以頁面上控件將全部被覆蓋,只有顯示的圖片。