FileUpload Save Images In Database In ASP.NET

This example explains how to Save Images In Sqlserver Database In Asp.Net Using File Upload Control.
I am Uploading Images using FileUpload Control and saving or storing them in SQL Server database in ASP.NET with C# and VB.NET.

FileUpload Save Images In Database In ASP.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 picture.
3. Image column to store image in binary format.

After uploading and saving images in database, pics 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

Html markup of the page look like
<form id="form1" runat="server">
<asp:TextBox ID="txtName" runat="server" Width="95px">
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Label ID="lblMessage" runat="server">
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload"/>

Write this code in Click Event of Upload Button
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";

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

Hope this helps

You can download the sample code from this post

Other ASP.NET and GridView articles:

ASP.NET Edit or update multiple records/rows in gridview with checkbox

Delete multiple rows records in Gridview with checkbox and confirmation

LinkButton in GridView and QueryString in ASP.NET to pass/transfer variable and data

Highlight gridview row on mouse over using javascript in and C# c-sharp

Read write word document with FileStream StreamWriter
If you like this post than join us or share


Anonymous said...

This comment has been removed by a blog administrator.

Anonymous said...

i got error when i follow exactly what u given, the error is "The name (image.size)does not exist in the current context", how i going to solve it. i using C#

Unknown said...


I have not used imge.size anywhere in the code
check ur code again it might be ImageSize instead

Anonymous said...

this is really very usefull..thanks..

Anonymous said...

very usefull code

jnana said...

its one of the very useful Technique

Anonymous said...

this article helps me a lot...and i'm really very thankful to you for providing the best programming...

Anonymous said...

i want upload files using file upload control to store in sql server and also the uploaded files i want see using grind view and download to save another place or device how i can do place send me the code

Anonymous said...

Wow dude, thanks heaps for this man , this was a really great help... along with your other tutorials... =) One thing though, can i know how to resize the image that is stored or do you have to resize when its extracted out ? Thanks for any help you can give man =)

Anonymous said...

hi, i have a problem, when i press the btnUpload_Click in the internet explorer

show "Internet Explorer cannot display the webpage"

please what's the problem , I don't understand

Anonymous said...

Hi how to resize the image after
upload .. ..

Unknown said...

hi amit

thanks ..

Anonymous said...

hello amit,

what is the datatype of image field in the database is it blob file or not?thank you....

Anonymous said...

hi thanks a lot for the code ..
but plz tell me hoe to resize the image before converting it into byte code .. ..

thanks a lot . ...

Anonymous said...

Please write the else part.

if the user did not use the fileupload control, one default picture should save in the database.


sharmila said...

could you tell me how to display images in to gridview control as i am using above method for uploading images in to db

sharmila said...

This comment has been removed by a blog administrator.

Unknown said...


Hi Sharmila, Please refer this post to know how to Display Images In GridView From DataBase

Unknown said...

hi I m saving image path in data base and retrieving the image in gridview. Im getting all other enteries from database except the image Plz help...
Here is the code..

Chai T Charlie said...

Firstly - Thanks for this lesson.

I am using Visual Web Developer Express 2008. Experience = limited - a couple of months learning a little on most days. I use visual basic code.

I created database.
I placed controls default.aspx and labelled them according to lesson.

I copied + pasted VB code into button_click event.( For any newbies looking at this there were loads of errors - thankfully mainly where code needed to be written on one single line. )

However I still have a little problem. Would anyone be kind enough to help me please . .

( To be clear my header code in aspx.vb page is the default:
Partial Class _Default
Inherits System.Web.UI.Page )

Problems / error messages are:

"SqlConnection" is not defined
"SqlCommand" is not defined
"CommandType" is not declared
"SqlParameter" is not defined

I am very new to databases - a very little history with MySql and one week trying to learn MSSql in VWD. I think these errors are probably a simple problem relating to how I have managed my database or sqldatasource. The basic problem is that I am to new to this to understand what I have done wrong without some help.

Re the "SqlParamater", "SqlCommand" and "CommandType" errors - at a guess I think they might need me to set a paramater with an attached command - I know the screen in VWD but would need some helpful direction re the query. Or am I totally wrong about that?

Re the "SqlConnection" error - I think this is probably an elementary mistake I have made when creating the database.

I am using user interface VWD - if anyone can help I would be ever so ever so grateful for any advice posted here.

Thanks in advance for any helpful response.

Masanam said...

It is very useful to us. i have learned from this. I want how to display the image from the database using gridview control. please help me.


Unknown said...


Hi please read this post to know how to Display Images in GridView from DataBase in ASP.NET

Anonymous said...

the image column shows system byte[] instead the picture... any help ?

Anonymous said...

hello i am Anpurna gupta.
Thanks Amit. said...

hi..sir please me give me your e-mail address .
i have one problem related to gridview editing......
whene i run my page on browser, error occur during exicution of page.......

Anonymous said...

m getting a sqlexception while running this appears in the handler.ahsx file

it comes on...
SqlDataReader dReader = cmd.ExecuteReader();
it says...
The parameterized query '(@id int)Select pics from myimages where id=@id' expects the parameter '@id', which was not supplied.

i have tried to resolve it but in vain.
plz help asap

Anonymous said...

hi amit
i getting this erro while runnig ur code

String or binary data would be truncated.
The statement has been terminated.

plz help me
thanks in advance

Anonymous said...

Amit,it's really a good article..

Unknown said...


Compiler Error Message: CS0103: The name 'txtName' does not exist in the current context

Source Error:

Line 94: protected void Button1_Click(object sender, EventArgs e)
Line 95: {
Line 96: string strImageName = txtName.Text.ToString();
Line 97: if (FileUpload1.PostedFile != null &&
Line 98: FileUpload1.PostedFile.FileName != "")

Anonymous said...

Hello sir,

I'm getting this error:
"Invalid object name 'Images'. "

I've use ur tables name same as u say bt its nt wrkin..
plzz help me...

Diogo Pinheiro said...


Nice post. FileUpload1.PostedFile is allways null.. what am i missing ?

Anonymous said...

can you tell me how to create a download to put a file on on your page nd than create a download link or button for it.

Thanks in advance

Anele Mabheka said...

How can I use a FileUpload and upload the image to this;

Anele Mabheka said...

How can I use a FileUpload and upload the image to this;

Unknown said...

The parameterized query '(@ID int)Select ImageName,Image from Images where ID =@ID' expects the parameter '@ID', which was not supplied . how can i solve this error . please help me

Anonymous said...

its good but u haven't give code for displaying images on webpages from database..
plz give that plz..

Anonymous said...

got some errors......but is fine.

Xavier said...

It was a very helpful resource. it helped me get an insight in my project. thanks

Anonymous said...

thanks for coding... but can u tell me how can i see this uploaded image

Anonymous said...

wen i run dis appl den it shows an exception on configuration manger line.
plz help
i really need ur help.
dis is divya here.

Anonymous said...

hi thanks a lot for the code ..
but am getting an exception "Operand type clash: int is incompatible with image" and its pointing to result which holds the value of cmd.ExecuteNonQuery().. Plz Help
thanks a lot . ...

Anonymous said...

Thanks for this post,

but my btnUpload_Click seems to run twice , every time I upload an image , i got two records.

Someone advice ?


Anonymous said...

its not working. please help me,i m frustrated...hv been trying from 4 days...

simonessalamone said... mvc file upload

FileUltimate is an ASP.NET file upload control which you can add directly to your existing ASP.NET (.aspx) pages.The control renders a user interface similar to "Windows Explorer" within the page which displays the contents of the target folder and accepts multiple file uploads from users. Actions can be limited by permissions and quota limits on folders. During file uploading, detailed information such as transfer speed and estimated time of completion are displayed along with the progress bar. This ASP.NET upload control supports browser upload,ajax upload and flash upload modes.

Ifraheem Siddique Awan said...

Very working code I use it and it is working fine but there must be code file how to use that image again

cahayamataku petunjuk said...

i dont know how to upload document file using c# to mysql database..
cn you help me?

Anonymous said...


This code is very helpful, can you contact me about a similar project like this.


Naveen said...

Thanks for code

Anonymous said...

Guys this works!!!!thank u soo much,,amiT jaiN :):)to display images have a look at this code,,

Anonymous said...

Hai Mr. AMIT
me too a developer in .net but i am a beginner
i can understand the code but problem is i am unable to make with some of the code in the downloads. can you plz keep videos for the consluting codes
thank you

Anonymous said...

The uploaded image was uploaded TWICE!
kindly help me with this, Im using VB.NET,

everything works fine but the problem is the image inserted in the database twice!

Anonymous said...

i recommend this code for dynamic image to be placed in Crytastal Report using ASP.NET, make a temporary path for upload of image then upload it to Temp table once Crystal report is loading. Very useful thanks.

Vicky said...

Very Nice and usefull Post. Nicely documented. Keep up the good work.


Anonymous said...

This post is great.
If you have trouble running this script try adding using System.Data.SqlClient;
using System.Configuration;


Anonymous said...

"String or binary data would be truncated.
The statement has been terminated."

this type of exception occurs, How to solve this error?

Sajan jani said...

Error in Line Number 15... while i have given the proper string value which is copied from the database connection string...... kindly provide error free code.... thanx

Sajid Asghar

Unknown said...

@Sajid Asghar: What error you are getting ?, have you added reference to system.configuration namespace ? , add using System.Configuration in code behind

Anonymous said...

hey there Please help me out!. when i click on edit and update i get this error:

Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[NotSupportedException: Updating is not supported by data source 'SqlDataSource1' unless UpdateCommand is specified.]
System.Web.UI.WebControls.SqlDataSourceView.ExecuteUpdate(IDictionary keys, IDictionary values, IDictionary oldValues) +1648200
System.Web.UI.DataSourceView.Update(IDictionary keys, IDictionary values, IDictionary oldValues, DataSourceViewOperationCallback callback) +92
System.Web.UI.WebControls.GridView.HandleUpdate(GridViewRow row, Int32 rowIndex, Boolean causesValidation) +907
System.Web.UI.WebControls.GridView.HandleEvent(EventArgs e, Boolean causesValidation, String validationGroup) +704
System.Web.UI.WebControls.GridView.OnBubbleEvent(Object source, EventArgs e) +95
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.GridViewRow.OnBubbleEvent(Object source, EventArgs e) +123
System.Web.UI.Control.RaiseBubbleEvent(Object source, EventArgs args) +37
System.Web.UI.WebControls.LinkButton.OnCommand(CommandEventArgs e) +118
System.Web.UI.WebControls.LinkButton.RaisePostBackEvent(String eventArgument) +135
System.Web.UI.WebControls.LinkButton.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +10
System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +13
System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +175
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1565

Burhan said...

can you please help me. how to update text with the image.

Unknown said...

@Burhan: i didn't get what you are trying to do ?

Unknown said...

@Anonymous: What you are trying to edit and update ?

Anonymous said...

hey, when i click on edit. it will not allow me to edit the text. I think becuase i am using images? like edit the image and text together?

Deon said...

I used this code and it works fine. I would like to know if anyone has used in without the GridView version.

Deon said...

Make sure your parameters for ID and ImageName are set.
UpdateCommand="Update Images SET ImageName=@ImageName WHERE ID=@ID">

Anonymous said...

hai i am siddharth but my id not open . fatehpur

Delivery to Home said...

Useful, by the way code using add parameter in code behind.
Normally I use fix parameter in design then add value with parameter.defaultvalue.
Help me add more idea thank you

Anonymous said... is really helpful

but how can i upload an image with some text data??

Text data should also stored in database

Any Solution???

Prakash Bari said...

really helpful you solution
thanks sir...

Unknown said...

it is irretitive website redirect to another page automatic after few second

Find More Articles