Вы находитесь на странице: 1из 5

ASP.

NET Database Tutorial


This tutorial will show you how to save image to a SQL database using ASP.NET and C#. This tutorial need the sample database provided by MS SQL. Database:Northwind Table:Categories Please modify the connectionstring based on the environment of your computer. The sample as below: string strConnectionString = "Data Source=dev005;Initial Catalog=Northwind;User ID=sa;password=1234"; Then, you will need to import the System.IO and System.Data.SqlClient namespace. The System.IO namespace contains the FileInfo and FileStream Classes. They transfer image or file to stream and save to database. using System.Data.SqlClient; using System.IO; using System.Data; By clicking button of 'Upload', we will save the selected image into database. By clicking button of 'Show latest Image', the application will show the latest image from database on the page of Default.aspx. protected void Button1_Click(object sender, EventArgs e) { FileInfo imageInfo = new FileInfo(File1.Value.Trim()); if (!imageInfo.Exists) this.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>"); else { switch (imageInfo.Extension.ToUpper()) { case ".JPG": this.UpLoadImageFile(imageInfo); break; case ".GIF": this.UpLoadImageFile(imageInfo); break; case ".BMP": this.UpLoadImageFile(imageInfo); break; default: this.RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>"); break; } } } private void UpLoadImageFile(FileInfo info) { SqlConnection objConn = null; SqlCommand objCom = null; try { byte[] content = new byte[info.Length]; FileStream imagestream = info.OpenRead(); imagestream.Read(content, 0, content.Length); imagestream.Close();

objConn = new SqlConnection(strConnectionString); objCom = new SqlCommand("insert into Categories(CategoryName,Picture)values(@CategoryName,@Pi cture)", objConn); SqlParameter categorynameParameter = new SqlParameter("@CategoryName", SqlDbType.NVarChar); if (this.txtFileName.Text.Trim().Equals("")) categorynameParameter.Value = "Default"; else categorynameParameter.Value = this.txtFileName.Text.Trim(); objCom.Parameters.Add(categorynameParameter); SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image); pictureParameter.Value = content; objCom.Parameters.Add(pictureParameter); objConn.Open(); objCom.ExecuteNonQuery(); objConn.Close(); } catch (Exception ex) { throw new Exception(ex.Message); } finally { objConn.Close(); } } protected void Button2_Click(object sender, EventArgs e) { SqlConnection objConn = null; try { objConn = new SqlConnection(strConnectionString); SqlCommand Command = new SqlCommand("select * from Categories order by CategoryID DESC", objConn); objConn.Open(); SqlDataReader MyReader = Command.ExecuteReader(CommandBehavior.CloseConnection ); if (MyReader.HasRows == true) { MyReader.Read(); Response.ContentType = "text/HTML"; Response.BinaryWrite((byte[])MyReader["Picture"]); } else { this.RegisterClientScriptBlock("alertMsg", "<script>alert('No Image.');</script>"); } MyReader.Close(); }

catch (Exception ex) { throw new Exception(ex.Message); } }

The front end Default.aspx page looks something like this: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head runat="server"> <title>Default</title> </head> <body> <form id="form1" runat="server"> <div> <fieldset> <legend>Upload image to database</legend> <table> <tr> <td style="width: 464px"> File Name:<asp:TextBox ID="txtFileName" runat="server"></asp:TextBox></td> </tr> <tr> <td style="width: 464px"> <input id="File1" runat="server" type="file" /></td> </tr> <tr> <td style="width: 464px"> <asp:Button ID="Button1" runat="server" Text="Upload" OnClick="Button1_Click" /></td> </tr> </table> <br/> <table> <tr> <td style="width: 464px"> <asp:Button ID="Button2" runat="server" Text="show latest Image" OnClick="Button2_Click" /></td> </tr> </table> </fieldset> </div> </form> </body> </html>

The flow for the code behind page is as follows. using using using using using using using using using System; System.Data; System.Configuration; System.Web; System.Web.Security; System.Web.UI; System.Web.UI.WebControls; System.Web.UI.WebControls.WebParts; System.Web.UI.HtmlControls;

using System.IO; using System.Data.SqlClient; public partial class _Default : System.Web.UI.Page string strConnectionString = "Data Source=dev005;Initial Catalog=Northwind;User ID=sa;password=1234"; protected void Page_Load(object sender, EventArgs e)

protected void Button1_Click(object sender, EventArgs e) FileInfo imageInfo = new FileInfo(File1.Value.Trim()); if (!imageInfo.Exists) this.RegisterClientScriptBlock("alertMsg", "<script>alert('please select one image file.');</script>"); switch (imageInfo.Extension.ToUpper()) case ".JPG": this.UpLoadImageFile(imageInfo); break; case ".GIF": this.UpLoadImageFile(imageInfo); break; case ".BMP": this.UpLoadImageFile(imageInfo); break; default: this.RegisterClientScriptBlock("alertMsg", "<script>alert('file type error.');</script>"); break;

private void UpLoadImageFile(FileInfo info) SqlConnection objConn = null; SqlCommand objCom = null; byte[] content = new byte[info.Length]; FileStream imagestream = info.OpenRead(); imagestream.Read(content, 0, content.Length); imagestream.Close(); objConn = new SqlConnection(strConnectionString); objCom = new SqlCommand("insert into Categories(CategoryName,Picture)values(@CategoryName,@Picture)", objConn); SqlParameter categorynameParameter = new SqlParameter("@CategoryName", SqlDbType.NVarChar); if (this.txtFileName.Text.Trim().Equals(""))

categorynameParameter.Value = "Default"; categorynameParameter.Value = this.txtFileName.Text.Trim(); objCom.Parameters.Add(categorynameParameter); SqlParameter pictureParameter = new SqlParameter("@Picture", SqlDbType.Image); pictureParameter.Value = content; objCom.Parameters.Add(pictureParameter); objConn.Open(); objCom.ExecuteNonQuery(); objConn.Close(); catch (Exception ex) throw new Exception(ex.Message);

objConn.Close(); protected void Button2_Click(object sender, EventArgs e) SqlConnection objConn = null; objConn = new SqlConnection(strConnectionString); SqlCommand Command = new SqlCommand("select * from Categories order by CategoryID DESC", objConn); objConn.Open(); SqlDataReader MyReader = Command.ExecuteReader(CommandBehavior.CloseConnection); if (MyReader.HasRows == true) MyReader.Read(); Response.ContentType = "text/HTML"; Response.BinaryWrite((byte[])MyReader["Picture"]);

this.RegisterClientScriptBlock("alertMsg", "<script>alert('No Image.');</script>"); MyReader.Close(); catch (Exception ex) throw new Exception(ex.Message);

Вам также может понравиться