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.
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
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.
- Add a FileUpload Control
- A Button.
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
Post a Comment