利用ASP.NET的FileUpload上傳Binary資料的圖片,存放在Image欄位型態的資料庫裡,並且結合ashx handler來瀏覽圖片

利用ASP.NET的FileUpload上傳Binary資料的圖片,存放在Image欄位型態的資料庫裡,並且結合ashx handler來瀏覽圖片

這篇文章主要介紹如何將上傳的檔案以Binary Data存放在資料庫裡....

並由ashx handler來將存放在資料庫的Binary Data呈現出來...

中間也用了一個GridView以列表方式..顯示資料庫裡所有的圖片資料...

並以ajax方式非同步更新Image的url .連到ashx handler檔案呈現圖片...

首先先規劃一個資料表...如下圖所示:

BinaryImageDB

c#範例..分三個部分....

1.上傳圖片到資料庫

ImageToDB.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ImageToDB.aspx.cs" Inherits="ImageToDB" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:   
   5:  <html xmlns="http://www.w3.org/1999/xhtml" >
   6:  <head runat="server">
   7:      <title>ImageToDB</title>
   8:  </head>
   9:  <body>
  10:      <form id="form1" runat="server">
  11:      <div>
  12:          <asp:FileUpload ID="FileUpload1" runat="server" />
  13:          <br />
  14:          <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><asp:Button ID="Button1"
  15:              runat="server" OnClick="Button1_Click" Text="upload" /></div>
  16:      </form>
  17:  </body>
  18:  </html> 

ImageToDB.aspx.cs

   1:  using System;
   2:  using System.Data;
   3:  using System.Configuration;
   4:  using System.Collections;
   5:  using System.Web;
   6:  using System.Web.Security;
   7:  using System.Web.UI;
   8:  using System.Web.UI.WebControls;
   9:  using System.Web.UI.WebControls.WebParts;
  10:  using System.Web.UI.HtmlControls;
  11:  using System.Data.SqlClient;
  12:   
  13:  public partial class ImageToDB : System.Web.UI.Page
  14:  {
  15:      protected void Page_Load(object sender, EventArgs e)
  16:      {
  17:   
  18:      }
  19:      protected void Button1_Click(object sender, EventArgs e)
  20:      {
  21:          //判斷檔案是否存在
  22:          if (this.FileUpload1.HasFile)
  23:          {
  24:              //取得副檔名
  25:              string ExtName = System.IO.Path.GetExtension(this.FileUpload1.PostedFile.FileName).ToLower();
  26:              string MIME = "";
  27:   
  28:              switch (ExtName)
  29:              {
  30:                  case  ".gif":
  31:                      MIME = "image/gif";
  32:                      break;
  33:                  case ".jpg":
  34:                      MIME = "image/jpg";
  35:                      break;
  36:                  case ".png":
  37:                      MIME = "image/png";
  38:                      break;
  39:                  default:
  40:                      break;
  41:              }
  42:   
  43:              if (MIME != "")
  44:              {
  45:                  //寫入資料庫
  46:                  using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString))
  47:                  {
  48:                      string sql = "insert into [Image] ([MIMEType],[Alt],[Image]) values(@MIMEType,@Alt,@Image)";
  49:                      SqlCommand cmd = new SqlCommand(sql, conn);
  50:                      cmd.Parameters.Add("@MIMEType", SqlDbType.VarChar, 50).Value = MIME;
  51:                      cmd.Parameters.Add("@Alt", SqlDbType.NVarChar, 50).Value = this.TextBox1.Text;
  52:                      byte[] imagebyte = new byte[this.FileUpload1.PostedFile.InputStream.Length];
  53:                      this.FileUpload1.PostedFile.InputStream.Read(imagebyte,0,imagebyte.Length);
  54:                      cmd.Parameters.Add("@Image", SqlDbType.Image).Value = imagebyte;
  55:                      conn.Open();
  56:                      cmd.ExecuteNonQuery();
  57:                  }
  58:              }
  59:              else
  60:              {
  61:                  this.Page.Form.Controls.Add(new LiteralControl("<script>alert('副檔名有誤!')</script>"));
  62:              }
  63:          }
  64:      }
  65:  }

BinaryImageUpload

2.列表方式呈現資料庫的資料

ViewImage.aspx

   1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ViewImage.aspx.cs" Inherits="ViewImage" %>
   2:   
   3:  <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
   4:   
   5:  <html xmlns="http://www.w3.org/1999/xhtml" >
   6:  <head runat="server">
   7:      <title>ViewImage</title>
   8:  </head>
   9:  <body>
  10:      <form id="form1" runat="server">
  11:      <div>
  12:          <asp:ScriptManager ID="ScriptManager1" runat="server">
  13:          </asp:ScriptManager>
  14:          <asp:UpdatePanel ID="UpdatePanel1" runat="server">
  15:              <ContentTemplate>
  16:          <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="id"
  17:              DataSourceID="SqlDataSource1" Width="300px" OnRowCommand="GridView1_RowCommand">
  18:              <Columns>
  19:                  <asp:BoundField DataField="id" HeaderText="id" InsertVisible="False" ReadOnly="True"
  20:                      SortExpression="id" />
  21:                  <asp:BoundField DataField="MIMEType" HeaderText="MIMEType" SortExpression="MIMEType" />
  22:                  <asp:BoundField DataField="Alt" HeaderText="Alt" SortExpression="Alt" />
  23:                  <asp:TemplateField HeaderText="view">
  24:                      <ItemTemplate>
  25:                          <asp:Button ID="Button1" runat="server" CommandArgument='<%# Eval("id") %>' CommandName="btnView"
  26:                              Text="view" />
  27:                      </ItemTemplate>
  28:                  </asp:TemplateField>
  29:              </Columns>
  30:          </asp:GridView>
  31:                  <asp:Image ID="Image1" runat="server" />
  32:              </ContentTemplate>
  33:          </asp:UpdatePanel>
  34:          <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:DatabaseConnectionString %>"
  35:              SelectCommand="SELECT * FROM [Image]"></asp:SqlDataSource>
  36:      
  37:      </div>
  38:      </form>
  39:  </body>
  40:  </html>
ViewImage.aspx.cs
   1:  using System;
   2:  using System.Data;
   3:  using System.Configuration;
   4:  using System.Collections;
   5:  using System.Web;
   6:  using System.Web.Security;
   7:  using System.Web.UI;
   8:  using System.Web.UI.WebControls;
   9:  using System.Web.UI.WebControls.WebParts;
  10:  using System.Web.UI.HtmlControls;
  11:   
  12:  public partial class ViewImage : System.Web.UI.Page
  13:  {
  14:      protected void Page_Load(object sender, EventArgs e)
  15:      {
  16:   
  17:      }
  18:      protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
  19:      {
  20:          if (e.CommandName == "btnView")
  21:          {
  22:              this.Image1.ImageUrl = "ImageShow.ashx?id=" + e.CommandArgument.ToString();
  23:          }
  24:      }
  25:  }

3.顯示圖片的ashx檔

ImageShow.ashx

   1:  <%@ WebHandler Language="C#" Class="ImageShow" %>
   2:   
   3:  using System;
   4:  using System.Web;
   5:  using System.Data.SqlClient;
   6:  using System.Data;
   7:  using System.Configuration;
   8:   
   9:  public class ImageShow : IHttpHandler {
  10:      
  11:      public void ProcessRequest (HttpContext context) {
  12:   
  13:          int id = int.Parse(context.Request.QueryString["id"]);
  14:          using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString))
  15:          {
  16:              string sql = "select * from [Image] where id=@id";
  17:              SqlCommand cmd = new SqlCommand(sql, conn);
  18:              cmd.Parameters.Add("@id", SqlDbType.Int).Value = id;
  19:              conn.Open();
  20:              SqlDataReader dr = cmd.ExecuteReader();
  21:              if (dr.Read())
  22:              {
  23:                  context.Response.ContentType = dr["MIMEType"].ToString();
  24:                  context.Response.BinaryWrite((byte[])dr["Image"]);
  25:              }
  26:              dr.Close();
  27:          }
  28:      }
  29:   
  30:      public bool IsReusable {
  31:          get {
  32:              return false;
  33:          }
  34:      }
  35:   
  36:  }

執行結果:

BinaryImageView

參考來源:

http://www.beansoftware.com/ASP.NET-Tutorials/Binary-Files-To-Database.aspx

http://www.codeproject.com/KB/web-image/ImageBinaryStream.aspx