Header Ads

FileUpload Save Images in Database in ASP.NET C# VB.NET

In this example i am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.

Database is having a table named Images with three columns.
1. ID Numeric Primary key with Identity Increment.
2. ImageName Varchar to store Name of Image.
3. Image Image to store image in binary format.

After uploading and saving images in database, images are displayed in GridView.

To know how to display images in gridview from database, read my post mentioned below
Display Images In GridView From DataBase in ASP.NET C# VB.NET

Asp.net page like this

OnClick="btnUpload_Click" Text="Upload"/>

Write this code in Click Event of Upload Button in
C# Code behind

protected void btnUpload_Click(object sender, EventArgs e)
string strImageName = txtName.Text.ToString();
if (FileUpload1.PostedFile != null &&
FileUpload1.PostedFile.FileName != "")
byte[] imageSize = new byte
HttpPostedFile uploadedImage = FileUpload1.PostedFile;
(imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

// Create SQL Connection
SqlConnection con = new SqlConnection();
con.ConnectionString = ConfigurationManager.ConnectionStrings

// Create SQL Command

SqlCommand cmd = new SqlCommand();
cmd.CommandText = "INSERT INTO Images(ImageName,Image)" +
" VALUES (@ImageName,@Image)";
cmd.CommandType = CommandType.Text;
cmd.Connection = con;

SqlParameter ImageName = new SqlParameter
("@ImageName", SqlDbType.VarChar, 50);
ImageName.Value = strImageName.ToString();

SqlParameter UploadedImage = new SqlParameter
("@Image", SqlDbType.Image, imageSize.Length);
UploadedImage.Value = imageSize;
int result = cmd.ExecuteNonQuery();
if (result > 0)
lblMessage.Text = "File Uploaded";

Write this code in Click Event of Upload Button in
vb.net Code behind

Protected Sub btnUpload_Click
(ByVal sender As Object, ByVal e As EventArgs)

Dim strImageName As String = txtName.Text.ToString()
If FileUpload1.PostedFile IsNot Nothing AndAlso
FileUpload1.PostedFile.FileName <> "" Then

Dim imageSize As Byte() = New Byte
(FileUpload1.PostedFile.ContentLength - 1) {}

Dim uploadedImage__1 As HttpPostedFile =

uploadedImage__1.InputStream.Read(imageSize, 0,

' Create SQL Connection
Dim con As New SqlConnection()
con.ConnectionString =

' Create SQL Command

Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Images
(ImageName,Image) VALUES (@ImageName,@Image)"
cmd.CommandType = CommandType.Text
cmd.Connection = con

Dim ImageName As New SqlParameter
("@ImageName", SqlDbType.VarChar, 50)
ImageName.Value = strImageName.ToString()

Dim UploadedImage__2 As New SqlParameter
("@Image", SqlDbType.Image, imageSize.Length)
UploadedImage__2.Value = imageSize
Dim result As Integer = cmd.ExecuteNonQuery()
If result > 0 Then
lblMessage.Text = "File Uploaded"
End If
End If
End Sub

No comments:

Powered by Blogger.