Register Register Member Login Member Login Member Login Forgot Password ??
PHP , ASP , ASP.NET, VB.NET, C#, Java , jQuery , Android , iOS , Windows Phone
 

Registered : 109,027

HOME > Free Web Script > .NET > ASP.NET Upload file BLOB and Binary Data การอัพโหลดไฟล์ไบนารี่ด้วย ASP.NET



Clound SSD Virtual Server
 

ASP.NET Upload file BLOB and Binary Data การอัพโหลดไฟล์ไบนารี่ด้วย ASP.NET

  ASP.NET BLOB Upload file and Storing Binary Data บทความ ASP.NET Framework การใช้ ASP.NET ทำการ Upload ไฟล์รูปภาพ ลงในฐานข้อมูล Column หรือ Fields ของ Database โดยเก็บข้อมูลไฟล์ ในรูปแบบของ Binary Data ผ่าน Data Type Image ,Binary หรือ BLOB

ตัวอย่างนี้มีทั้งภาษา VB.NET และ C#

ความสามารถของ Script
- เก็บฟิวด์ชื่อและรูปภาพลงใน Binary Data ผ่าน Data Type ชื่อ Image,BLOB หรืออื่น ๆ ที่สามารถจัดเก็บในรูปแบบของ Binary
- Form สำหรับ Upload ข้อมูล
- Form สำหรับแสดงข้อมูลรูปภาพ ซึ่งดึงข้อมูล Binary Data จาก Image
- Form สำหรับการแก้ไขข้อมูลรูปภาพ และการบันทึกรูปภาพใหม่
- การยืนยันและการลบข้อมูล
- ตัวอย่างนี้จะใช้การ Query ข้อมูลผ่าน Parameters

Go to : .NET Parameterized Queries

ปกติแล้วการเก็บรูปภาพ หรืออัพโหลดรูปภาพจะนิยมทำการ Upload รูปภาพลงในโฟเดอร์ และมีการเก็บเพียงชื่อไฟล์หรือ path ลงใน ฐานข้อมูล ซึ่งวิธีนี้จะสะดวกต่อการจับเก็บและการนำไปใช้ รวมทั้งป้องกันไม่เปลืองเนื้อที่ของ Database ในการจัดเก็บด้วย ซึ่งการเรียกใช้งานก็สามารถอ้างอิงจาก Path ของรูปภาพได้เลย เช่น

Code
Me.ImgPic.ImageUrl = dt.Rows(0)("ImagePath")


แต่ในกรณีที่เราจัดเก็บรูปภาพทั้งหมดที่ถูกแปลงเป็น Binary Data แล้วลงในฐานข้อมูล Database จะไม่สามารถเรียกชื่อไฟล์นั้นได้โดงตรง เพราะข้อมูลที่ถูกจัดเก็บนั้นอยู่ในรูปแบบข้อมูล Binary แต่จะต้องสร้างไฟล์ ASP.NET (Web Form) สำหรับอ่าน Binary Data และแปลงมาเป็นรูปภาพอีกขั้นตอนหนึ่ง จากนั้นก็อ้างอิง Path จากไฟล์ WebForm นั้น ๆ เพื่อแสดงรูปภาพออกมาก

ViewImg.aspx
... Request.QueryString("ID")
Read and Write image Binary From Table


ซึ่งในไฟล์ ViewImage.aspx จะทำการอ่านข้อมูลที่ถูกจัดเก็บไว้ในรูปแบบของ Binary และทำการแสดงผลออกมาด้วยคำสั่ง

Response.ContentType = "image/jpg"
Response.BinaryWrite(Binary-Data)


และตอนเรียกใช้งาน

Code
Me.ImgPic.ImageUrl = "ViewImg.aspx?FilesID=123"


จากตัวอย่างจะเห็นว่าเราจะต้องสร้างไฟล์ ViewImg.aspx ไว้อ่านค่ารูปภาพ โดยส่งค่าผ่าน id และเมื่อได้รูปภาพออกมาแล้ว ก็จะได้ค่า Binary กลับ และเมื่อเราใช้ Control ที่ชื่อว่า Image ในการรับค่า Binary ผลลัพธ์ก็จะแสดงรูปภาพนั้นออกมา วิธีนี้จะสามารถป้องกันการ Save รูปภาพผ่าน Web Browser ได้อีกด้วย

การจัดเก็บข้อมูลรูปภาพผ่าน Binary ของ BLOB Type หรือ Image Type ไม่ค่อยได้รับความนิยม อันเนื่องจาก ประมาณการจัดเก็บและการนำไปใช้ค่อนข้างจะยาก และมีปัญหาเรื่อง Database บวม เมื่อข้อมูลรูปภาพมีปริมาณมาก สำหรับตัวอย่างนี้ผมได้ทอสอบเขียนบน Visual Studio กับ SQL Server Database แต่ทั้งนี้สามารถประยุกต์ใช้กับ Database อื่น ๆ ได้ เช่น Access , MySQL หรือ Oracle ซึ่งรูปแบบ Syntax ของการเชื่อมต่อกับฐานข้อมูลต่าง ๆ สามารถศึกษาได้จาก บทความ/บทเรียน ASP.NET

Go to : ASP.NET System.Data.OleDb - Parameter Query (OleDbParameter)
Go to : ASP.NET MySql.Data.MySqlClient - Parameter Query (MySqlParameter)
Go to : ASP.NET System.Data.SqlClient - Parameter Query (SqlParameter)
Go to : ASP.NET System.Data.OracleClient - Parameter Query (OracleParameter)

เริ่มต้นสร้าง Project ด้วย Visual Studio สามารถใช้ได้กับ .NET ทุกเวอร์ชั่น แต่อาจจะต้องดัดแปลงแก้ไขในบางจุด

ASP.NET BLOB & Binary


ให้สร้างตารางบนฐานข้อมูลของคุณดังนี้ ในที่นี้จะใช้ชื่อตารางว่า files

Table
USE [mydatabase]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_PADDING ON
GO
CREATE TABLE [dbo].[files](
	[FilesID] [int] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](100) NULL,
	[FilesName] [image] NULL,
	[FilesType] [varchar](20) NULL,
 CONSTRAINT [PK_files] PRIMARY KEY CLUSTERED 
(
	[FilesID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO
SET ANSI_PADDING OFF


เอา Query นี้ไปรันเพื่อสร้างตารางข้อมูล โดยแก้ไขชื่อ database ตรง USE [mydatabase] ให้ถูกต้องจากนั้นก็รันได้เลย








Code สำหรับ VB.NET

Default.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <input id="btnReset" type="reset" value="Reset" /></div>
       </asp:Panel>
    
    </form>
</body>
</html>


Default.aspx.vb
Imports System.Data
Imports System.Data.SqlClient

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Me.pnlForm.Visible = False

        If Me.fUpload.HasFile = False Or Me.txtName.Text = "" Then
            Me.lblStatus.Text = "Please input Name and Chooes File."
        Else

            '*** Read Binary Data ***'
            Dim imbByte(fUpload.PostedFile.InputStream.Length) As Byte
            fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length)

            '*** MimeType ***'
            Dim ExtType As String = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower()
            Dim strMIME As String = Nothing
            Select Case ExtType
                Case ".gif"
                    strMIME = "image/gif"
                Case ".jpg", ".jpeg", ".jpe"
                    strMIME = "image/jpeg"
                Case ".png"
                    strMIME = "image/png"
                Case Else
                    Me.lblStatus.Text = "Invalid file type."
                    Exit Sub
            End Select

            '*** Insert to Database ***'
            Dim objConn As New SqlConnection
            Dim strConnString, strSQL As String

            strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"

            strSQL = "INSERT INTO files (Name,FilesName,FilesType) " & _
            " VALUES " & _
            " (@sName,@sFilesName,@sFilesType)"
            objConn.ConnectionString = strConnString
            objConn.Open()

            Dim objCmd As New SqlCommand(strSQL, objConn)
            objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = Me.txtName.Text
            objCmd.Parameters.Add("@sFilesName", SqlDbType.Binary).Value = imbByte
            objCmd.Parameters.Add("@sFilesType", SqlDbType.VarChar).Value = strMIME
            objCmd.ExecuteNonQuery()

            objConn.Close()
            objConn = Nothing

            Me.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
        End If
    End Sub

End Class


ViewImg.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ViewImg.aspx.vb" Inherits="ViewImg" %>


ViewImg.aspx.vb
Imports System.Data
Imports System.Data.SqlClient

Partial Class ViewImg
    Inherits System.Web.UI.Page

    Dim objConn As New SqlConnection
    Dim objCmd As SqlCommand
    Dim strConnString, strSQL As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()

        '*** DataTable ***'
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New DataTable
        strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID "
        dtAdapter = New SqlDataAdapter(strSQL, objConn)
        objCmd = dtAdapter.SelectCommand
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        dtAdapter.Fill(dt)

        If dt.Rows.Count > 0 Then
            Response.ContentType = dt.Rows(0)("FilesType").ToString()
            Response.BinaryWrite(dt.Rows(0)("FilesName"))
        End If

        dt = Nothing
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

End Class


ListPicture.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="ListPicture.aspx.vb" Inherits="ListPicture" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
 <asp:GridView id="myGridView" runat="server" AutoGenerateColumns="False">
	<Columns>
	<asp:TemplateField HeaderText="ID">
		<ItemTemplate>
			<asp:Label id="lblFilesID" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Name">
		<ItemTemplate>
			<asp:Label id="lblName" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Picture">
		<ItemTemplate>
			<asp:Image ID="ImgPic" runat="server" />
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Edit">
		<ItemTemplate>
            <asp:HyperLink ID="hplEdit" runat="server">Edit</asp:HyperLink>
        </ItemTemplate>
	</asp:TemplateField>

	</Columns>
</asp:GridView>
    
    </div>
    </form>
</body>
</html>


ListPicture.aspx.vb
Imports System.Data
Imports System.Data.SqlClient

Partial Class ListPicture
    Inherits System.Web.UI.Page

    Dim objConn As SqlConnection
    Dim objCmd As SqlCommand

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        Dim strConnString As String
        strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn = New SqlConnection(strConnString)
        objConn.Open()

        BindData()
    End Sub

    Protected Sub BindData()
        Dim strSQL As String
        strSQL = "SELECT * FROM files ORDER BY FilesID ASC"

        Dim dtReader As SqlDataReader
        objCmd = New SqlCommand(strSQL, objConn)
        dtReader = objCmd.ExecuteReader()

        '*** BindData to GridView ***'
        myGridView.DataSource = dtReader
        myGridView.DataBind()

        dtReader.Close()
        dtReader = Nothing
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

    Protected Sub myGridView_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles myGridView.RowDataBound
        '*** FilesID ***'
        Dim lblFilesID As Label = DirectCast(e.Row.FindControl("lblFilesID"), Label)
        If Not IsNothing(lblFilesID) Then
            lblFilesID.Text = e.Row.DataItem("FilesID")
        End If

        '*** Name ***'
        Dim lblName As Label = DirectCast(e.Row.FindControl("lblName"), Label)
        If Not IsNothing(lblName) Then
            lblName.Text = e.Row.DataItem("Name")
        End If

        '*** Picture ***'
        Dim ImgPic As Image = DirectCast(e.Row.FindControl("ImgPic"), Image)
        If Not IsNothing(ImgPic) Then
            ImgPic.ImageUrl = "ViewImg.aspx?FilesID= " & e.Row.DataItem("FilesID")
        End If

        '*** Hyperlink ***'
        Dim hplEdit As HyperLink = DirectCast(e.Row.FindControl("hplEdit"), HyperLink)
        If Not IsNothing(hplEdit) Then
            hplEdit.Text = "Edit"
            hplEdit.NavigateUrl = "Edit.aspx?FilesID=" & e.Row.DataItem("FilesID")
        End If

    End Sub

End Class


Edit.aspx
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Edit.aspx.vb" Inherits="Edit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
<form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Image ID="ImgPic" runat="server" />
            <br />
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" />
            <input id="btnReset" type="reset" value="Reset" />
            <asp:Button ID="btnDel" runat="server" Text="Delete" />            
       </asp:Panel>
    </div>
    </form>
</body>
</html>


Edit.aspx.vb
Imports System.Data
Imports System.Data.SqlClient

Partial Class Edit
    Inherits System.Web.UI.Page

    Dim objConn As New SqlConnection
    Dim objCmd As SqlCommand
    Dim strConnString, strSQL As String

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        Me.btnDel.Attributes.Add("OnClick", "return confirm('Are you sure delete?');")

        strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;"
        objConn.ConnectionString = strConnString
        objConn.Open()

        If Not Page.IsPostBack() Then
            ViewData()
        End If
    End Sub

    Protected Sub ViewData()
        '*** DataTable ***'
        Dim dtAdapter As SqlDataAdapter
        Dim dt As New DataTable
        strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID "
        dtAdapter = New SqlDataAdapter(strSQL, objConn)
        objCmd = dtAdapter.SelectCommand
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        dtAdapter.Fill(dt)

        If dt.Rows.Count > 0 Then
            Me.ImgPic.ImageUrl = "ViewImg.aspx?FilesID=" & dt.Rows(0)("FilesID")
            Me.txtName.Text = dt.Rows(0)("Name")
        End If

        dt = Nothing
    End Sub

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        Me.pnlForm.Visible = False

        If Me.txtName.Text = "" Then
            Me.lblStatus.Text = "Please input Name."
        Else

            '*** Update Name ***'
            strSQL = "UPDATE files SET Name = @sName " & _
                   " WHERE FilesID = @sFilesID "

            objCmd = New SqlCommand(strSQL, objConn)
            objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = Me.txtName.Text
            objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
            objCmd.ExecuteNonQuery()

            '*** Update Picture ***'
            If Me.fUpload.HasFile = True Then
                '*** Read Binary Data ***'
                Dim imbByte(fUpload.PostedFile.InputStream.Length) As Byte
                fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length)

                '*** MimeType ***'
                Dim ExtType As String = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower()
                Dim strMIME As String = Nothing
                Select Case ExtType
                    Case ".gif"
                        strMIME = "image/gif"
                    Case ".jpg", ".jpeg", ".jpe"
                        strMIME = "image/jpeg"
                    Case ".png"
                        strMIME = "image/png"
                    Case Else
                        Me.lblStatus.Text = "Invalid file type."
                        Exit Sub
                End Select

                strSQL = "UPDATE files SET FilesName = @sFilesName , FilesType = @sFilesType  " & _
                       " WHERE FilesID = @sFilesID "

                objCmd = New SqlCommand(strSQL, objConn)
                objCmd.Parameters.Add("@sFilesName", SqlDbType.Binary).Value = imbByte
                objCmd.Parameters.Add("@sFilesType", SqlDbType.VarChar).Value = strMIME
                objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
                objCmd.ExecuteNonQuery()

            End If

            Me.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
        End If
    End Sub

    Protected Sub btnDel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnDel.Click
        Me.pnlForm.Visible = False
        '*** Delete Rows ***'
        strSQL = "DELETE FROM files  " & _
               " WHERE FilesID = @sFilesID "

        objCmd = New SqlCommand(strSQL, objConn)
        objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString("FilesID")
        objCmd.ExecuteNonQuery()
        Me.lblStatus.Text = "Delete Successfully. Click <a href='ListPicture.aspx'>here</a> to view."
    End Sub

    Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload
        objConn.Close()
        objConn = Nothing
    End Sub

End Class





Code สำหรับ C#

Default.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ASPNetBLOB._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" 
                onclick="btnUpload_Click" />
            <input id="btnReset" type="reset" value="Reset" /></div>
       </asp:Panel>
    
    </form>
</body>
</html>


Default.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace ASPNetBLOB
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            this.pnlForm.Visible = false;

            if (this.fUpload.HasFile == false | string.IsNullOrEmpty(this.txtName.Text))
            {
                this.lblStatus.Text = "Please input Name and Chooes File.";

            }
            else
            {
                //*** Read Binary Data ***'
                byte[] imbByte = new byte[fUpload.PostedFile.InputStream.Length + 1];
                fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length);

                //*** MimeType ***'
                string ExtType = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower();
                string strMIME = null;
                switch (ExtType)
                {
                    case ".gif":
                        strMIME = "image/gif";
                        break;
                    case ".jpg":
                    case ".jpeg":
                    case ".jpe":
                        strMIME = "image/jpeg";
                        break;
                    case ".png":
                        strMIME = "image/png";
                        break;
                    default:
                        this.lblStatus.Text = "Invalid file type.";
                        return;
                }

                //*** Insert to Database ***'
                SqlConnection objConn = new SqlConnection();
                string strConnString = null;
                string strSQL = null;

                strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";

                strSQL = "INSERT INTO files (Name,FilesName,FilesType) VALUES (@sName,@sFilesName,@sFilesType)";
                objConn.ConnectionString = strConnString;
                objConn.Open();

                SqlCommand objCmd = new SqlCommand(strSQL, objConn);
                objCmd.Parameters.Add("@sName", SqlDbType.Binary).Value = this.txtName.Text;
                objCmd.Parameters.Add("@sFilesName", SqlDbType.VarChar).Value = imbByte;
                objCmd.Parameters.Add("@sFilesType", SqlDbType.Int).Value = strMIME;
                objCmd.ExecuteNonQuery();

                objConn.Close();
                objConn = null;

                this.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view.";
            }
        }

    }
}


ViewImg.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ViewImg.aspx.cs" Inherits="ASPNetBLOB.ViewImg" %>


ViewImg.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace ASPNetBLOB
{
    public partial class ViewImg : System.Web.UI.Page
    {
        SqlConnection objConn = new SqlConnection();
        SqlCommand objCmd;
        string strConnString;
        string strSQL;

        protected void Page_Load(object sender, EventArgs e)
        {
            strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
            objConn.ConnectionString = strConnString;
            objConn.Open();

            //*** DataTable ***'
            SqlDataAdapter dtAdapter = default(SqlDataAdapter);
            DataTable dt = new DataTable();
            strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID ";
            dtAdapter = new SqlDataAdapter(strSQL, objConn);
            objCmd = dtAdapter.SelectCommand;
            objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString["FilesID"].ToString();
            dtAdapter.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                Response.ContentType = dt.Rows[0]["FilesType"].ToString();
                Response.BinaryWrite((byte[])dt.Rows[0]["FilesName"]);
            }

            dt = null;
        }

        protected void Page_Unload(object sender, System.EventArgs e)
        {
            objConn.Close();
            objConn = null;
        }
    }
}


ListPicture.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ListPicture.aspx.cs" Inherits="ASPNetBLOB.ListPicture" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    
 <asp:GridView id="myGridView" runat="server" AutoGenerateColumns="False" 
            onrowdatabound="myGridView_RowDataBound">
	<Columns>
	<asp:TemplateField HeaderText="ID">
		<ItemTemplate>
			<asp:Label id="lblFilesID" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Name">
		<ItemTemplate>
			<asp:Label id="lblName" runat="server"></asp:Label>
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Picture">
		<ItemTemplate>
			<asp:Image ID="ImgPic" runat="server" />
		</ItemTemplate>
	</asp:TemplateField>

	<asp:TemplateField HeaderText="Edit">
		<ItemTemplate>
            <asp:HyperLink ID="hplEdit" runat="server">Edit</asp:HyperLink>
        </ItemTemplate>
	</asp:TemplateField>

	</Columns>
</asp:GridView>
    
    </div>
    </form>
</body>
</html>


ListPicture.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace ASPNetBLOB
{
    public partial class ListPicture : System.Web.UI.Page
    {
        SqlConnection objConn;
        SqlCommand objCmd;
        protected void Page_Load(object sender, EventArgs e)
        {
            string strConnString = null;
            strConnString = "Server=localhost;UID=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
            objConn = new SqlConnection(strConnString);
            objConn.Open();

            BindData();
        }

        protected void BindData()
        {
            string strSQL = null;
            strSQL = "SELECT * FROM files ORDER BY FilesID ASC";

            SqlDataReader dtReader = default(SqlDataReader);
            objCmd = new SqlCommand(strSQL, objConn);
            dtReader = objCmd.ExecuteReader();

            //*** BindData to GridView ***'
            myGridView.DataSource = dtReader;
            myGridView.DataBind();

            dtReader.Close();
            dtReader = null;
        }

        protected void myGridView_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //*** FilesID ***'
            Label lblFilesID = (Label)e.Row.FindControl("lblFilesID");
            if ((lblFilesID != null))
            {
                lblFilesID.Text = DataBinder.Eval(e.Row.DataItem, "FilesID").ToString();
            }

            //*** Name ***'
            Label lblName = (Label)e.Row.FindControl("lblName");
            if ((lblName != null))
            {
                lblName.Text = DataBinder.Eval(e.Row.DataItem, "Name").ToString();
            }

            //*** Picture ***'
            Image ImgPic = (Image)e.Row.FindControl("ImgPic");
            if ((ImgPic != null))
            {
                ImgPic.ImageUrl = "ViewImg.aspx?FilesID= " + DataBinder.Eval(e.Row.DataItem, "FilesID").ToString();
            }

            //*** Hyperlink ***'
            HyperLink hplEdit = (HyperLink)e.Row.FindControl("hplEdit");
            if ((hplEdit != null))
            {
                hplEdit.Text = "Edit";
                hplEdit.NavigateUrl = "Edit.aspx?FilesID=" + DataBinder.Eval(e.Row.DataItem, "FilesID").ToString();
            }
        }

        protected void Page_Unload(object sender, EventArgs e)
        {
            objConn.Close();
            objConn = null;
        }
    }
}


Edit.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Edit.aspx.cs" Inherits="ASPNetBLOB.Edit" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ThaiCreate.Com Tutorials</title>
</head>
<body>
<form id="form1" runat="server">
    <div>
    
        <asp:Label ID="lblStatus" runat="server" 
            Text="Please input Name and Chooes File. "></asp:Label>
        <br />
        
        <asp:Panel ID="pnlForm" Visible="true" runat="server">
            <asp:Image ID="ImgPic" runat="server" />
            <br />
            <asp:Label ID="lblName" runat="server" Text="Name :" Width="50px"></asp:Label>
            <asp:TextBox ID="txtName" runat="server"></asp:TextBox>
            <br />
            <asp:Label ID="lblPicture" runat="server" Text="Picture :" Width="50px"></asp:Label>
            <asp:FileUpload ID="fUpload" runat="server" />
            <br />
            <asp:Button ID="btnUpload" runat="server" Text="Upload" 
                onclick="btnUpload_Click" />
            <input id="btnReset" type="reset" value="Reset" />
            <asp:Button ID="btnDel" runat="server" Text="Delete" onclick="btnDel_Click" />            
       </asp:Panel>
    </div>
    </form>
</body>
</html>


Edit.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;

namespace ASPNetBLOB
{
    public partial class Edit : System.Web.UI.Page
    {
        SqlConnection objConn = new SqlConnection();
        SqlCommand objCmd;
        string strConnString;

        string strSQL;
        protected void Page_Load(object sender, EventArgs e)
        {
            this.btnDel.Attributes.Add("OnClick", "return confirm('Are you sure delete?');");

            strConnString = "Server=localhost;Uid=sa;PASSWORD=;database=mydatabase;Max Pool Size=400;Connect Timeout=600;";
            objConn.ConnectionString = strConnString;
            objConn.Open();

            if (!Page.IsPostBack)
            {
                ViewData();
            }
        }

        protected void ViewData()
        {
            //*** DataTable ***'
            SqlDataAdapter dtAdapter = default(SqlDataAdapter);
            DataTable dt = new DataTable();
            strSQL = "SELECT * FROM files WHERE FilesID = @sFilesID ";
            dtAdapter = new SqlDataAdapter(strSQL, objConn);
            objCmd = dtAdapter.SelectCommand;
            objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString["FilesID"];
            dtAdapter.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                this.ImgPic.ImageUrl = "ViewImg.aspx?FilesID=" + dt.Rows[0]["FilesID"];
                this.txtName.Text = dt.Rows[0]["Name"].ToString();
            }

            dt = null;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            this.pnlForm.Visible = false;

            if (string.IsNullOrEmpty(this.txtName.Text))
            {
                this.lblStatus.Text = "Please input Name.";

            }
            else
            {
                //*** Update Name ***'
                strSQL = "UPDATE files SET Name = @sName WHERE FilesID = @sFilesID ";

                objCmd = new SqlCommand(strSQL, objConn);
                objCmd.Parameters.Add("@sName", SqlDbType.VarChar).Value = this.txtName.Text;
                objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString["FilesID"];
                objCmd.ExecuteNonQuery();

                //*** Update Picture ***'
                if (this.fUpload.HasFile == true)
                {
                    //*** Read Binary Data ***'
                    byte[] imbByte = new byte[fUpload.PostedFile.InputStream.Length + 1];
                    fUpload.PostedFile.InputStream.Read(imbByte, 0, imbByte.Length);

                    //*** MimeType ***'
                    string ExtType = System.IO.Path.GetExtension(fUpload.PostedFile.FileName).ToLower();
                    string strMIME = null;
                    switch (ExtType)
                    {
                        case ".gif":
                            strMIME = "image/gif";
                            break;
                        case ".jpg":
                        case ".jpeg":
                        case ".jpe":
                            strMIME = "image/jpeg";
                            break;
                        case ".png":
                            strMIME = "image/png";
                            break;
                        default:
                            this.lblStatus.Text = "Invalid file type.";
                            return;
                    }

                    strSQL = "UPDATE files SET FilesName = @sFilesName , FilesType = @sFilesType WHERE FilesID = @sFilesID ";

                    objCmd = new SqlCommand(strSQL, objConn);
                    objCmd.Parameters.Add("@sFilesName", SqlDbType.Binary).Value = imbByte;
                    objCmd.Parameters.Add("@sFilesType", SqlDbType.VarChar).Value = strMIME;
                    objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString["FilesID"];
                    objCmd.ExecuteNonQuery();

                }

                this.lblStatus.Text = "File Upload Successfully. Click <a href='ListPicture.aspx'>here</a> to view.";
            }
        }

        protected void btnDel_Click(object sender, EventArgs e)
        {
            this.pnlForm.Visible = false;
            //*** Delete Rows ***'
            strSQL = "DELETE FROM files WHERE FilesID = @sFilesID ";

            objCmd = new SqlCommand(strSQL, objConn);
            objCmd.Parameters.Add("@sFilesID", SqlDbType.Int).Value = Request.QueryString["FilesID"];
            objCmd.ExecuteNonQuery();
            this.lblStatus.Text = "Delete Successfully. Click <a href='ListPicture.aspx'>here</a> to view.";

        }

        protected void Page_Unload(object sender, System.EventArgs e)
        {
            objConn.Close();
            objConn = null;
        }

    }
}









Screenshot

ASP.NET BLOB & Binary

Form สำหรับการ Upload ข้อมูล

ASP.NET BLOB & Binary

Form สำหรับการแสดงข้อมูล และเมนูคลิกสำหรับการแก้ไข

ASP.NET BLOB & Binary

Form สำหรับการแก้ไขข้อมูล

ASP.NET BLOB & Binary

กรณีที่มีการคลิกลบข้อมูล

บทความอื่น ๆ เกี่ยวกับการ Upload โดยใช้ BLOB Binary

Go to : ASP.NET Access BLOB Binary Data and Parameterized Query
Go to : ASP.NET MySQL BLOB Binary Data and Parameterized Query
Go to : ASP.NET SQL Server BLOB Binary Data and Parameterized Query
Go to : ASP.NET Oracle BLOB Binary Data and Parameterized Query

บทความอื่น ๆ ที่เกี่ยวข้อง
Go to : ASP.NET Upload File
Go to : ASP.NET Upload file to Database


   
Share

Bookmark.
  Score Rating :
  Create Date : 2011-05-27 14:00:18
  View : 26,280
  Download : No files
     
Sponsored Links
ASP.NET Register / Login Form / Reset Password / Update Profile (VB.NET , C#)
การทำระบบสมาชิก register form / login form และ form สำหรับ reset password พร้อมทั้งการ update ข้อมูล profile ด้วย asp.net กับ ฐานข้อมูล sql server database
Rating : Update : 2017-03-24 21:08:57
ASP.NET สร้าง WebBoard (เว็บบอร์ด) กระทู้หรือกระดานถาม-ตอบ (by VB.NET , C#)
บทความ asp.net กับการสร้างระบบ webboard หรือกระดานถามตอบ สำหรับการตั้งกระทู้ และการแสดงความคิดเห็นในกระทู้
Rating : Update : 2017-03-24 21:07:51
สร้างระบบ Shopping Cart ด้วย ASP.NET แบบง่าย ๆ Step by Step (VB.NET ,C#)
บทความ asp.net กับการสร้างระบบ shopping cart หรือระบบตะกร้าสินค้า step by step แบบง่าย ๆ ด้วยภาษา vb.net และ c#
Rating : Update : 2017-03-24 21:06:37
VB.NET C# Login Form (Windows App)
สร้าง Form Login บน Windows App สำหรับ Windows Form Application ในการตรวจสอบ Username และ Password
Rating : Update : 2012-05-20 07:54:58
ThaiCreate.Com Forum


Comunity Forum Free Web Script
Jobs Freelance Free Uploads
Free Web Hosting Free Tools

สอน PHP ผ่าน Youtube ฟรี
สอน Android การเขียนโปรแกรม Android
สอน Windows Phone การเขียนโปรแกรม Windows Phone 7 และ 8
สอน iOS การเขียนโปรแกรม iPhone, iPad
สอน Java การเขียนโปรแกรม ภาษา Java
สอน Java GUI การเขียนโปรแกรม ภาษา Java GUI
สอน JSP การเขียนโปรแกรม ภาษา Java
สอน jQuery การเขียนโปรแกรม ภาษา jQuery
สอน .Net การเขียนโปรแกรม ภาษา .Net
Free Tutorial
สอน Google Maps Api
สอน Windows Service
สอน Entity Framework
สอน Android
สอน Java เขียน Java
Java GUI Swing
สอน JSP (Web App)
iOS (iPhone,iPad)
Windows Phone
Windows Azure
Windows Store
Laravel Framework
Yii PHP Framework
สอน jQuery
สอน jQuery กับ Ajax
สอน PHP OOP (Vdo)
Ajax Tutorials
SQL Tutorials
สอน SQL (Part 2)
JavaScript Tutorial
Javascript Tips
VBScript Tutorial
VBScript Validation
Microsoft Access
MySQL Tutorials
-- Stored Procedure
MariaDB Database
SQL Server Tutorial
SQL Server 2005
SQL Server 2008
SQL Server 2012
-- Stored Procedure
Oracle Database
-- Stored Procedure
SVN (Subversion)
แนวทางการทำ SEO
ปรับแต่งเว็บให้โหลดเร็ว


Hit Link
   







Load balance : Server 01
ThaiCreate.Com Logo
© www.ThaiCreate.Com. 2003-2024 All Rights Reserved.
ไทยครีเอทบริการ จัดทำดูแลแก้ไข Web Application ทุกรูปแบบ (PHP, .Net Application, VB.Net, C#)
[Conditions Privacy Statement] ติดต่อโฆษณา 081-987-6107 อัตราราคา คลิกที่นี่