How to Upload Image to DB in SQL

Follow the steps below to upload Image to SQL in your Asp.Net website

1) Create a Table in you DB.

CREATE TABLE [dbo].[CustomerDetails] (
    [ID]           INT            IDENTITY (1, 1) NOT NULL,
    [CustomerName] NVARCHAR (MAX) NULL,

    [Address] NVARCHAR (MAX) NULL,
     [Latitude]     FLOAT (53)     NULL,
    [Longitude]    FLOAT (53)     NULL,
    [Image]        IMAGE          NULL,
    CONSTRAINT [PK_CustomerDetails] PRIMARY KEY CLUSTERED ([ID] ASC)
);


2) Create a new application.

  1. Add a FileUpload Control
  2. A Button.
3) In your Button click event  paste the code below.

try
            {
                if (FileUpload1.HasFile)
                {
                    //getting length of uploaded file
                    int length = FileUpload1.PostedFile.ContentLength;
                    //create a byte array to store the binary image data
                    byte[] imgbyte = new byte[length];
                    //store the currently selected file in memeory
                    HttpPostedFile img = FileUpload1.PostedFile;
                    //set the binary data
                    img.InputStream.Read(imgbyte, 0, length);
                    con.Open();
                    SqlCommand cmd = new SqlCommand("insert into CustomerDetails (Image) value (@Image)", con);
                       cmd.Parameters.AddWithValue("@Image", imgbyte);
                      cmd.Connection = con;
                     cmd.ExecuteNonQuery();
                     Response.Redirect(Request.Url.AbsoluteUri);
                  
                    con.Close();
                }
            }
            catch (Exception)
            {
            }
}


That's all.! Next post on how to retrieve the Image from DB , with and without Handler file


Comments

Popular posts from this blog

How to show multiple markers on Google maps from database in ASP.Net

How to Solve Bootstrap Tooltip disappearing inside a updatepanel control when a button is click or in postback in ASP.NET

Show Bootstrap Popup Modal from inside a Repeater in Asp.Net