
<% @Import Namespace="System" %>
<% @Import Namespace="System.IO" %>
<% @Import Namespace="System.Data" %>
<% @Import Namespace="System.Data.SqlClient" %>
<HTML>
  <HEAD>
		<title>保存图片到SQL Server数据库示例<</title>
		<script language=C# runat=server>
		
			void Button_Submit(System.Object sender, System.EventArgs e) 
			{
			  // HttpPostedFile对象，用于读取图象文件属性
			  HttpPostedFile UpFile = UP_FILE.PostedFile;

			  // FileLength 变量存储图片的字节大小
			  int FileLength = UpFile.ContentLength;

			  try
			  {
				if (FileLength == 0)
				{
					txtMessage.Text = "<b>您未选择上传的文件</b>";
				}
				else
				{
					// 创建存储图片文件的临时 Byte 数组
					Byte[] FileByteArray = new Byte[FileLength];

					// 建立数据流对象
					Stream StreamObject = UpFile.InputStream;  
    
					// 读取图象文件数据，FileByteArray为数据储存体，0为数据指针位置、FileLnegth为数据长度
					StreamObject.Read(FileByteArray,0,FileLength);   

					// 数据库操作
					string ConnStr = System.Configuration.ConfigurationSettings.AppSettings["ConnectionSqlServer"];
					string query = "INSERT INTO ImageTable (ImageData, ImageContentType, ImageDescription, ImageSize) VALUES (@ImageData, @ImageContentType, @ImageDescription, @ImageSize)";
					SqlCommand myCommand = new SqlCommand(query, new SqlConnection(ConnStr));

					// 添加各项参数并赋值
					myCommand.Parameters.Add("@ImageData", SqlDbType.Image);
					myCommand.Parameters.Add("@ImageContentType", SqlDbType.VarChar, 50);
					myCommand.Parameters.Add("@ImageDescription", SqlDbType.VarChar, 200);
					myCommand.Parameters.Add("@ImageSize", SqlDbType.BigInt);
					myCommand.Parameters["@ImageData"].Value = FileByteArray;
					myCommand.Parameters["@ImageContentType"].Value = UpFile.ContentType;
					myCommand.Parameters["@ImageDescription"].Value = txtDescription.Text;
					myCommand.Parameters["@ImageSize"].Value = FileLength;
					
					// 执行数据库操作
					myCommand.Connection.Open();
					myCommand.ExecuteNonQuery();
					myCommand.Connection.Close();

					// 提示上传成功
					txtMessage.Text = "<b>上传文件成功</b>";
				}
			} 
			catch (Exception ex) 
			{
				// 使用 Label 标签显示异常
				txtMessage.Text = ex.Message.ToString();
			}
		}

		</script>
</HEAD>
	<BODY>
		<FORM id="Form1" runat="server">
			<h3>保存图片到SQL Server数据库示例</h3>
			请选择要上传的图片：<input id="UP_FILE" type="file" size="24" name="UP_FILE" runat="server">
			<br><br>
			请输入图片文件说明：<asp:textbox id="txtDescription" Runat="server"></asp:textbox>
			<br><br>
			<asp:button 
				id="SubmitButton" 
				onclick="Button_Submit" 
				Runat="server" 
				Text="上传图片" 
				Width="239">
			</asp:button>
			<br><br>
			<asp:label id="txtMessage" Runat="server" ForeColor="red"></asp:label><br>
			<br><br>
		</FORM>
	</BODY>
</HTML>
