using System;
using System.Configuration;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Web;
using System.IO;
using System.Web.SessionState;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;

namespace DBImages
{
	public class UploadImage : System.Web.UI.Page
	{
		protected System.Web.UI.WebControls.Button UploadBtn;
		protected System.Web.UI.WebControls.RequiredFieldValidator RequiredFieldValidator1;
		protected System.Web.UI.HtmlControls.HtmlInputText txtImgName;
		protected System.Web.UI.HtmlControls.HtmlInputFile UploadFile;
	
		public UploadImage()	{ 	}

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

		public void UploadBtn_Click(object sender, System.EventArgs e)
		{
			if (Page.IsValid)	//save the image
			{
				Stream imgStream = UploadFile.PostedFile.InputStream;
				int imgLen = UploadFile.PostedFile.ContentLength;
				string imgContentType = UploadFile.PostedFile.ContentType;
				string imgName = txtImgName.Value;
				byte[] imgBinaryData = new byte[imgLen];
				int n = imgStream.Read(imgBinaryData,0,imgLen);
				
				int RowsAffected = SaveToDB( imgName, imgBinaryData,imgContentType);
				if ( RowsAffected>0 )
				{
					Response.Write("<BR>文件成功保存");
				}
				else
				{
					Response.Write("<BR>上传文件时出错");
				}

			}
		}


		private int SaveToDB(string imgName, byte[] imgbin, string imgcontenttype)
		{
			//use the web.config to store the connection string
			SqlConnection connection = new SqlConnection(ConfigurationSettings.AppSettings["DSN"]);
			SqlCommand command = new SqlCommand( "INSERT INTO Image (img_name,img_data,img_contenttype) VALUES ( @img_name, @img_data,@img_contenttype )", connection );

			SqlParameter param0 = new SqlParameter( "@img_name", SqlDbType.VarChar,50 );
			param0.Value = imgName;
			command.Parameters.Add( param0 );

			SqlParameter param1 = new SqlParameter( "@img_data", SqlDbType.Image );
			param1.Value = imgbin;
			command.Parameters.Add( param1 );

			SqlParameter param2 = new SqlParameter( "@img_contenttype", SqlDbType.VarChar,50 );
			param2.Value = imgcontenttype;
			command.Parameters.Add( param2 );

			connection.Open();
			int numRowsAffected = command.ExecuteNonQuery();
			connection.Close();

			return numRowsAffected;
		}
	}
}
