Save Images into Sql Server Database Table using Asp.Net FileUpload Control C# VB.Net

This article will explain how one can insert or save images into Sql Server Database table using Asp.net FileUpload control. You may ask why we will save or store images into Sql Server Database table instead of a server folder? The answer is its easy to use, easy to manage, easy to backup as well as easy to program. But one thing you have to keep in mind that you need to extend the size of your Database rather than your regular size. Always deleting images from server folder is a hectic job where security will play a great role but if you store images into Sql Server database you can remove images or related images by issuing a simple delete Sql command.

Objective/Outcome:
Save Images into Sql Server Database Table using asp.net FileUpload Control CSHARP VB.Net

To do the Example First Create the below Table:

CREATE TABLE [dbo].[Images](
	[ID] [bigint] IDENTITY(1,1) NOT NULL,
	[Name] [varchar](max) NULL,
	[Content] [image] NULL,
	[Size] [bigint] NULL,
	[Type] [varchar](max) NULL,
 CONSTRAINT [PK_Images] PRIMARY KEY CLUSTERED 
(
	[ID] 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]

Now Modify the Web.Config File to Connect to Database:

<configuration>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=TESTDB;Trusted_Connection=yes;" providerName="System.Data.SqlClient"/>
    <!--<add name="BONConnection" connectionString="Data Source=XXX.com;Initial Catalog=DBNAME;User Id=UserName;Password=YourPassword;" providerName="System.Data.SqlClient" />-->
  </connectionStrings>
...................
...................

Note: If you use windows authentication then use the first key. Otherwise use second key line. Update server name, Database name, User name, Password as per your settings.

Now add a FileUpload Control and a Button to Upload:

        Name:        
        <asp:TextBox runat="server" ID="txt_Image_Name"></asp:TextBox><br />
    
        Image Path:
        <asp:FileUpload runat="server" ID="FileUpload1" /><br />

        <asp:Button runat="server" ID="cmd_Upload" Text="Upload Image" OnClick="cmd_Upload_Click" />

Now under cmd_Upload Click Event write below Code:
C# Code:

    protected void cmd_Upload_Click(object sender, EventArgs e)
    {
        string s_Image_Name = txt_Image_Name.Text.ToString();
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
            byte[] n_Image_Size = new byte[FileUpload1.PostedFile.ContentLength];
            HttpPostedFile Posted_Image = FileUpload1.PostedFile;
            Posted_Image.InputStream.Read(n_Image_Size, 0, (int)FileUpload1.PostedFile.ContentLength);

            SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString);

            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO Images(Name,[Content],Size,Type)" +
                              " VALUES (@Image_Name,@Image_Content,@Image_Size,@Image_Type)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;

            SqlParameter Image_Name = new SqlParameter("@Image_Name", SqlDbType.VarChar, 500);
            Image_Name.Value = txt_Image_Name.Text;
            cmd.Parameters.Add(Image_Name);

            SqlParameter Image_Content = new SqlParameter("@Image_Content", SqlDbType.Image, n_Image_Size.Length);
            Image_Content.Value = n_Image_Size;
            cmd.Parameters.Add(Image_Content);

            SqlParameter Image_Size = new SqlParameter("@Image_Size", SqlDbType.BigInt, 99999);
            Image_Size.Value = FileUpload1.PostedFile.ContentLength;
            cmd.Parameters.Add(Image_Size);

            SqlParameter Image_Type = new SqlParameter("@Image_Type", SqlDbType.VarChar, 500);
            Image_Type.Value = FileUpload1.PostedFile.ContentType;
            cmd.Parameters.Add(Image_Type);


            conn.Open();
            cmd.ExecuteNonQuery();
            conn.Close();
        }
    }

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” namespaces.

VB.Net Code:

    Protected Sub cmd_Upload_Click(sender As Object, e As System.EventArgs)
        Dim s_Image_Name As String = txt_Image_Name.Text.ToString()
        If FileUpload1.PostedFile IsNot Nothing AndAlso FileUpload1.PostedFile.FileName <> "" Then
            Dim n_Image_Size As Byte() = New Byte(FileUpload1.PostedFile.ContentLength - 1) {}
            Dim Posted_Image As HttpPostedFile = FileUpload1.PostedFile
            Posted_Image.InputStream.Read(n_Image_Size, 0, CInt(FileUpload1.PostedFile.ContentLength))

            Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("DBConnection").ConnectionString)

            Dim cmd As New SqlCommand()
            cmd.CommandText = "INSERT INTO Images(Name,[Content],Size,Type)" & " VALUES (@Image_Name,@Image_Content,@Image_Size,@Image_Type)"
            cmd.CommandType = CommandType.Text
            cmd.Connection = conn

            Dim Image_Name As New SqlParameter("@Image_Name", SqlDbType.VarChar, 500)
            Image_Name.Value = txt_Image_Name.Text
            cmd.Parameters.Add(Image_Name)

            Dim Image_Content As New SqlParameter("@Image_Content", SqlDbType.Image, n_Image_Size.Length)
            Image_Content.Value = n_Image_Size
            cmd.Parameters.Add(Image_Content)

            Dim Image_Size As New SqlParameter("@Image_Size", SqlDbType.BigInt, 99999)
            Image_Size.Value = FileUpload1.PostedFile.ContentLength
            cmd.Parameters.Add(Image_Size)

            Dim Image_Type As New SqlParameter("@Image_Type", SqlDbType.VarChar, 500)
            Image_Type.Value = FileUpload1.PostedFile.ContentType
            cmd.Parameters.Add(Image_Type)


            conn.Open()
            cmd.ExecuteNonQuery()
            conn.Close()
        End If

    End Sub

Note: Don’t forget to add “System.Data”, “System.Data.SqlClient”, “System.Configuration” namespaces.

Now run the project & check the table content field. Hope you are successful.

Download Code Example C#        Download Code Example VB.Net

Posted in .Net, Asp.net, C#, Database, SQL Server, VB.Net
3 comments on “Save Images into Sql Server Database Table using Asp.Net FileUpload Control C# VB.Net
  1. Lara Fox says:

    THANKS!

  2. Kho D ir says:

    Thanks Dude!! it’s work for me… Great πŸ™‚

  3. Dave says:

    The code is uploading two entries into the database everytime I press the upload button and I can’t figure out why, please HELP.

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code
     
 

*