Wednesday, August 5, 2015

Asp.net: Save image in Binary format in Sql Server Database using C#, VB.net

In this tutorial I am going to explain how to save image in Binary format in Sql Server Database using C#, VB.net

Description:
In the previous article I have explained Insert record into Database using Gridview inAsp.net.

I have created table Movie to store the information of movie like name, genre, cost and poster of movie. Movie poster will be stored in binary format.

Implementation:
Create a table Movie

Asp.net:  Save image in Binary format in Sql Server Database using C#, VB.net


Create store procedure to insert data into database table.

Create PROCEDURE Sp_InsertMovieDetail
(
@name varchar(100),
@genre varchar(100),
@cost int,
@poster varbinary(max)
)
AS
BEGIN
            SET NOCOUNT ON;
Insert into Movie(Name,Genre,Cost,Poster) values(@name,@genre,@cost,@poster)
END
GO
Add a webform to project/website. Drag and drop the required control from toolbox to webform i.e. fileupload, textbox and button control.

HTML Markup of webform:
      <table>
        <tr><td>Movie Name :</td><td>
            <asp:TextBox ID="txtname" runat="server"></asp:TextBox></td></tr>
         <tr><td>Genre :</td><td><asp:TextBox ID="txtgenre" runat="server"></asp:TextBox></td></tr>
         <tr><td>Movie budget :</td><td><asp:TextBox ID="txtcost" runat="server"></asp:TextBox></td></tr>
         <tr><td>Upload Poster :</td><td>
             <asp:FileUpload ID="fileuploadposter" runat="server" /></td></tr>
         <tr><td></td><td>
             <asp:Button ID="btnsubmit" runat="server" Text="Submit" /></td></tr>
         <tr><td></td><td></td></tr>
    </table>

Add the namespace to code file
C#:
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;

VB:
Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
Imports System.IO

Submit the data
On button clock write the code to submit the data to table and clear the controls.

C#:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["connection"].ToString());

protected void btnsubmit_Click(object sender, EventArgs e)
    {
        try
        {
            if (fileuploadposter.HasFile)
            {
                string filepath = Server.MapPath("~/images/") + Guid.NewGuid() + fileuploadposter.PostedFile.FileName;
                fileuploadposter.PostedFile.SaveAs(filepath);
                FileStream fS = new FileStream(filepath, FileMode.Open, FileAccess.Read);
                BinaryReader br = new BinaryReader(fS);
                byte[] bytes = br.ReadBytes(Convert.ToInt32(fS.Length));
                fS.Close();
                br.Close();
                fS.Close();
                SqlCommand cmd = new SqlCommand("Sp_InsertMovieDetail", con);
                cmd.CommandType = CommandType.StoredProcedure;
                con.Open();
                cmd.Parameters.AddWithValue("@name", txtname.Text);
                cmd.Parameters.AddWithValue("@genre", txtgenre.Text);
                cmd.Parameters.AddWithValue("@cost", txtcost.Text);
                cmd.Parameters.AddWithValue("@poster", bytes);
                cmd.ExecuteNonQuery();
                con.Close();
                cmd.Dispose();
                ClearControl();
                Response.Write("<script type=\"text/javascript\">alert('Record Insert Successfully!!!');</script>");
            }
        }
        catch(Exception ex)
        { }
    }
    public void ClearControl()
    {
        txtcost.Text = "";
        txtgenre.Text = "";
        txtname.Text = "";
    }

VB:
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("connection").ToString())
 
Protected Sub btnsubmit_Click(sender As Object, e As EventArgs) Handles btnsubmit.Click
        Try
            If fileuploadposter.HasFile Then
                Dim filepath As String = Server.MapPath("~/images/") & Guid.NewGuid().ToString() & fileuploadposter.PostedFile.FileName
                fileuploadposter.PostedFile.SaveAs(filepath)
                Dim fS As New FileStream(filepath, FileMode.Open, FileAccess.Read)
                Dim br As New BinaryReader(fS)
                Dim bytes As Byte() = br.ReadBytes(Convert.ToInt32(fS.Length))
                fS.Close()
                br.Close()
                fS.Close()
                Dim cmd As New SqlCommand("Sp_InsertMovieDetail", con)
                cmd.CommandType = CommandType.StoredProcedure
                con.Open()
                cmd.Parameters.AddWithValue("@name", txtname.Text)
                cmd.Parameters.AddWithValue("@genre", txtgenre.Text)
                cmd.Parameters.AddWithValue("@cost", txtcost.Text)
                cmd.Parameters.AddWithValue("@poster", bytes)
                cmd.ExecuteNonQuery()
                con.Close()
                cmd.Dispose()
                ClearControl()
                Response.Write("<script type=""text/javascript"">alert('Record Insert Successfully!!!');</script>")
            End If
        Catch ex As Exception
        End Try
    End Sub
    Public Sub ClearControl()
        txtcost.Text = ""
        txtgenre.Text = ""
        txtname.Text = ""
    End Sub
Build, run the project and check via insert data into database.

 Result:
Asp.net:  Save image in Binary format in Sql Server Database using C#, VB.net
   In this article we have learn how to save image in Binary format in Sql Server database  in asp.net (C#, VB). I hope you enjoyed this article.

4 comments: