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">
<div>
<asp:TextBox ID="txtName" runat="server" Width="95px">
</asp:TextBox>
<asp:FileUpload ID="FileUpload1" runat="server"/>
<asp:Label ID="lblMessage" runat="server">
</asp:Label>
<asp:Button ID="btnUpload" runat="server" 
            OnClick="btnUpload_Click" Text="Upload"/>
</div>
</form>

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
                 [FileUpload1.PostedFile.ContentLength];
  HttpPostedFile uploadedImage = FileUpload1.PostedFile;
  uploadedImage.InputStream.Read
     (imageSize, 0, (int)FileUpload1.PostedFile.ContentLength);

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

 // 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();
 cmd.Parameters.Add(ImageName);

 SqlParameter UploadedImage = new SqlParameter
               ("@Image", SqlDbType.Image, imageSize.Length);
 UploadedImage.Value = imageSize;
 cmd.Parameters.Add(UploadedImage);
 con.Open();
 int result = cmd.ExecuteNonQuery();
 con.Close();
 if (result > 0)
 lblMessage.Text = "File Uploaded";
 GridView1.DataBind();
 }
}

VB.NET Code
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 = 
                                 FileUpload1.PostedFile

        uploadedImage__1.InputStream.Read(imageSize, 0, 
              CInt(FileUpload1.PostedFile.ContentLength))
        
        ' Create SQL Connection 
        Dim con As New SqlConnection()
        con.ConnectionString = 
                 ConfigurationManager.ConnectionStrings
                  ("ConnectionString").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()
        cmd.Parameters.Add(ImageName)
        
        Dim UploadedImage__2 As New SqlParameter
            ("@Image", SqlDbType.Image, imageSize.Length)
        UploadedImage__2.Value = imageSize
        cmd.Parameters.Add(UploadedImage__2)
        con.Open()
        Dim result As Integer = cmd.ExecuteNonQuery()
        con.Close()
        If result > 0 Then
            lblMessage.Text = "File Uploaded"
        End If
        GridView1.DataBind()
    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 asp.net and C# c-sharp

Read write word document with FileStream StreamWriter

69 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. 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 asp.net C#

    ReplyDelete
  3. @Anonymous:

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

    ReplyDelete
  4. this is really very usefull..thanks..

    ReplyDelete
  5. very usefull code

    ReplyDelete
  6. its one of the very useful Technique
    thanks

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

    ReplyDelete
  8. 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

    ReplyDelete
  9. 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 =)

    ReplyDelete
  10. 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

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

    ReplyDelete
  12. hello amit,

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

    ReplyDelete
  13. 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 . ...

    ReplyDelete
  14. Please write the else part.

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

    Uttam

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

    ReplyDelete
  16. This comment has been removed by a blog administrator.

    ReplyDelete
  17. @Sharmila:

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

    ReplyDelete
  18. 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..

    ReplyDelete
  19. Firstly - Thanks for this lesson.

    I am using Visual Web Developer Express 2008. Experience = limited - a couple of months learning a little asp.net 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.

    ReplyDelete
  20. 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.

    Thanks!

    ReplyDelete
  21. @masanam:

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

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

    ReplyDelete
  23. hello i am Anpurna gupta.
    Thanks Amit.

    ReplyDelete
  24. 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.......

    ReplyDelete
  25. hi
    m getting a sqlexception while running this code....it 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

    ReplyDelete
  26. 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

    ReplyDelete
  27. Amit,it's really a good article..

    ReplyDelete
  28. I

    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 != "")

    ReplyDelete
  29. 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...

    ReplyDelete
  30. Hello,

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

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

    Thanks in advance

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

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

    ReplyDelete
  34. 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

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

    ReplyDelete
  36. got some errors......but is fine.

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

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

    ReplyDelete
  39. hiii...
    amit
    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.

    ReplyDelete
  40. 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 . ...

    ReplyDelete
  41. Hi,
    Thanks for this post,

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

    Someone advice ?

    Regards

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

    ReplyDelete
  43. asp.net 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.

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

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

    ReplyDelete
  46. Hi,

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

    Thanks
    718-399-0961

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

    http://csharpdotnetfreak.blogspot.com/2009/07/display-images-gridview-from-database.html

    ReplyDelete
  48. 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
    Divya

    ReplyDelete
  49. 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!

    ReplyDelete
  50. 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.

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

    Vicky

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

    Adrian

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

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

    ReplyDelete
  54. 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

    Regards
    Sajid Asghar

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

    ReplyDelete
  56. 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

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

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

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

    ReplyDelete
  60. 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?

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

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

    ReplyDelete
  63. hai i am siddharth but my id not open . fatehpur

    ReplyDelete
  64. 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

    ReplyDelete
  65. Hi..it is really helpful

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

    Text data should also stored in database

    Any Solution???

    ReplyDelete
  66. hiiii
    really helpful you solution
    thanks sir...

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

    ReplyDelete