In this article I will explain with an example, how to upload and save (insert) images to SQL Server Database in ASP.Internet using C# and VB.Net.

Prototype files volition be uploaded and then volition be saved (inserted) to SQL Server database tabular array in Binary format. The saved (inserted) Image files will be retrieved and displayed in ASP.Internet GridView along with feature to Zoom the Prototype using jQuery.

Database

This article makes use of a table named tblFiles whose schema is defined as follows.

How to save ( insert ) Image in Database in ASP.Net using C# and VB.Net

Note : You tin download the database table SQL by clicking the download link below.

HTML Markup

The following HTML Markup consists of an ASP.Cyberspace FileUpload control, Push, a GridView and an HTML DIV.

< asp : FileUpload ID ="FileUpload1" runat ="server" />

< asp : Button ID ="btnUpload" runat ="server" Text ="Upload" OnClick ="Upload" />

< hr />

< asp : GridView ID ="gvImages" runat ="server" AutoGenerateColumns ="false" OnRowDataBound ="OnRowDataBound">

< Columns >

< asp : BoundField DataField ="Id" HeaderText ="Image Id" />

< asp : BoundField DataField ="Name" HeaderText ="Name" />

< asp : TemplateField HeaderText ="Image">

< ItemTemplate >

< asp : Paradigm ID ="Image1" runat ="server" />

</ ItemTemplate >

</ asp : TemplateField >

</ Columns >

</ asp : GridView >

< div id ="dialog" style =" display : none">

</ div >

Namespaces

You will demand to import the following namespaces.

C#

using System.IO;

using System.Information;

using System.Configuration;

using System.Information.SqlClient;

VB.Net

Imports System.IO

Imports Organization.Data

Imports Arrangement.Configuration

Imports System.Data.SqlClient

Displaying Binary Images from database in ASP.Net GridView

Within the Page Load upshot handler, the records from the database table are fetched and are used to populate the GridView control.

Inside the RowDataBound upshot of the GridView, the Binary data i.e. Byte Array is converted into a BASE64 string and assigned to the ImageUrl property of the Image control within the GridView.

C#

protected void Page_Load(object sender, EventArgs due east)

{

if (!this.IsPostBack)

    {

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection conn = new SqlConnection(constr))

        {

using (SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM tblFiles", conn))

            {

DataTable dt = new DataTable();

                sda.Make full(dt);

                gvImages.DataSource = dt;

                gvImages.DataBind();

            }

        }

    }

}

protected void OnRowDataBound(object sender, GridViewRowEventArgs due east)

{

if (e.Row.RowType == DataControlRowType.DataRow)

    {

DataRowView dr = (DataRowView)eastward.Row.DataItem;

string imageUrl = "data:image/jpg;base64," + Catechumen.ToBase64String((byte[])dr["Data"]);

        (e.Row.FindControl("Image1") as Image).ImageUrl = imageUrl;

    }

}

VB.Internet

Protected Sub Page_Load(ByVal sender Equally Object, ByVal due east As EventArgs) Handles Me.Load

If Not Me.IsPostBack So

Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

Using conn Equally SqlConnection = New SqlConnection(constr)

Using sda Equally SqlDataAdapter = New SqlDataAdapter("SELECT * FROM tblFiles", conn)

Dim dt Every bit DataTable = New DataTable()

                sda.Fill(dt)

                gvImages.DataSource = dt

                gvImages.DataBind()

Terminate Using

End Using

Stop If

End Sub

Protected Sub OnRowDataBound(ByVal sender Every bit Object, ByVal due east Equally GridViewRowEventArgs)

If e.Row.RowType = DataControlRowType.DataRow Then

Dim dr As DataRowView = CType(e.Row.DataItem, DataRowView)

Dim imageUrl Equally String = "data:image/jpg;base64," & Convert.ToBase64String(CType(dr("Data"), Byte()))

CType(e.Row.FindControl("Image1"), Image).ImageUrl = imageUrl

End If

End Sub

Uploading and saving Image in Binary format in SQL Server database in ASP.Net

The following event handler gets chosen when an Image file is selected and the Upload Push button is clicked.

The uploaded Epitome file is converted to an Array of Bytes using BinaryReader class and finally is inserted into the database table.

C#

protected void Upload(object sender, EventArgs eastward)

{

byte[] bytes;

using (BinaryReader br = new BinaryReader(FileUpload1.PostedFile.InputStream))

    {

        bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength);

    }

string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;

using (SqlConnection conn = new SqlConnection(constr))

    {

string sql = "INSERT INTO tblFiles VALUES(@Name, @ContentType, @Data)";

using (SqlCommand cmd = new SqlCommand(sql, conn))

        {

            cmd.Parameters.AddWithValue("@Proper name", Path.GetFileName(FileUpload1.PostedFile.FileName));

            cmd.Parameters.AddWithValue("@ContentType", FileUpload1.PostedFile.ContentType);

            cmd.Parameters.AddWithValue("@Information", bytes);

            conn.Open();

            cmd.ExecuteNonQuery();

            conn.Close();

        }

    }

    Response.Redirect(Request.Url.AbsoluteUri);

}

VB.Cyberspace

Protected Sub Upload(ByVal sender As Object, ByVal eastward As EventArgs)

Dim bytes Equally Byte()

Using br As BinaryReader = New BinaryReader(FileUpload1.PostedFile.InputStream)

        bytes = br.ReadBytes(FileUpload1.PostedFile.ContentLength)

Terminate Using

Dim constr As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString

Using conn As SqlConnection = New SqlConnection(constr)

Dim sql As String = "INSERT INTO tblFiles VALUES(@Name, @ContentType, @Data)"

Using cmd Every bit SqlCommand = New SqlCommand(sql, conn)

            cmd.Parameters.AddWithValue("@Proper name", Path.GetFileName(FileUpload1.PostedFile.FileName))

            cmd.Parameters.AddWithValue("@ContentType", FileUpload1.PostedFile.ContentType)

            cmd.Parameters.AddWithValue("@Data", bytes)

            conn.Open()

            cmd.ExecuteNonQuery()

            conn.Close()

End Using

End Using

    Response.Redirect(Request.Url.AbsoluteUri)

End Sub

Implement Zoom feature when Image is clicked using jQuery

A jQuery click outcome handler is assigned to all the HTML Epitome elements within the GridView. When an HTML Image element is clicked, the Epitome chemical element is cloned and displayed in larger size within a jQuery UI Model Popup.

< script type ="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jquery/one.8.three/jquery.min.js"></ script >

< link rel ="stylesheet" href ="https://ajax.googleapis.com/ajax/libs/jqueryui/ane.eight.24/themes/start/jquery-ui.css" />

< script type ="text/javascript" src ="https://ajax.googleapis.com/ajax/libs/jqueryui/i.eight.24/jquery-ui.min.js"></ script >

< script type ="text/javascript">

    $(function () {

        $("#dialog").dialog({

            autoOpen: false,

            modal: true,

            height: 600,

            width: 600,

            title: "Zoomed Image"

        });

        $("[id*=gvImages] img").click(office () {

            $('#dialog').html('');

            $('#dialog').append($(this).clone());

            $('#dialog').dialog('open up');

        });

    });

</ script >

Screenshot

How to save ( insert ) Image in Database in ASP.Net using C# and VB.Net

Downloads