Skip to main content

How to save images in database and retrieve image from database

Hello friends
In this article, we will explore how to store images in the database and then display those images along with the other server controls
Today I am going to show how you can save   image from web page to database using asp File Upload Control and retrieve same image . There might be various approaches for this I am going show one of them  

Using handlers : by converting image into binary format




I am going to a build a form, with the person’s details and his photo along with it, or for that case, display the image in an ASP.NET server control along with other controls?

Let us start off by first creating a sample database and adding a table to it. We will call the database and the table will be called ‘Tbl_Emp’

Database structure will be like this

            


Step 1: Create a new asp.net website and add a webpage to it    
Step2: Drag and drop two textbox controls. Also drag drop a File Upload control and two button control to upload the selected image on button click and to retrieve record from database. Dropdown List to select list ID which will be used to retrieve selected record from database
Aspx page code will look like below
<div>
      Enter ID  <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox><br />
      Enter Name <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox><br />
      Enter Pic  <asp:FileUpload ID="FileUpload1" runat="server" /><br />
      <asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" /><br >

       <asp:Image ID="Image1"  runat="server" Height="137px" Width="130px" /><br />
       
        <asp:DropDownList ID="TextBox3" runat="server">
        </asp:DropDownList>
       
        <asp:Button ID="Button2" runat="server" Text="Search" onclick="Button2_Click" />

    </div>



Step3: code on .cs page
On my code there are three methods
Filldropdown() : used to fill dropdown
Button1_Click : used to save image into database
Button2_Click : used to retrieve image from database


 static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            filldropdown();
        }
    }

    public void filldropdown()
    {
        SqlCommand cmd = new SqlCommand("Select EmpID from Tbl_Emp", con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        TextBox3.Items.Clear();
        if (dr.HasRows)
        {
            //TextBox3.DataSource = dr["EmpID"].ToString();
            //TextBox3.DataBind();

            while (dr.Read())
            {
                TextBox3.Items.Add(dr["EmpID"].ToString());
            }
        }
        con.Close();
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("insert into Tbl_Emp values(@id,@name,@image)",con);
        cmd.Parameters.AddWithValue("@id", TextBox1.Text);
        cmd.Parameters.AddWithValue("@name", TextBox2.Text);

        int img = FileUpload1.PostedFile.ContentLength;

        byte[] msdata = new byte[img];

        FileUpload1.PostedFile.InputStream.Read(msdata,0,img);

        cmd.Parameters.AddWithValue("@image", msdata);

        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.ExecuteNonQuery();

        con.Close();

        filldropdown();

        Response.Write("Data Saved ....");

    }
    protected void Button2_Click(object sender, EventArgs e)
    {
        SqlCommand cmd = new SqlCommand("select * from Tbl_Emp where EmpID=@id", con);
        cmd.Parameters.AddWithValue("@id", TextBox3.Text);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        SqlDataReader dr = cmd.ExecuteReader();
        if (dr.HasRows && dr.Read())
        {
            TextBox1.Text = dr["EmpID"].ToString();
            TextBox2.Text = dr["EmpName"].ToString();
            Image1.ImageUrl = "Handler.ashx?EmpID=" + TextBox3.Text;
        }
        else
        {
            Response.Write("Record With This ID Note Found");
        }
      
    }

Step 4: In order to display the image on the page, we will create an Http handler. To do so, right click project > Add New Item > Generic Handler > Handler.ashx. The code shown below, uses the Request.QueryString[“id”] to retrieve the EmpID from it. The ID is then passed to  this handler from drop on button 2 click
<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Data;
using System.Data.SqlClient;
using System.Web;

public class Handler : IHttpHandler {

    static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=E:\websites\HttpHandlerDemo\App_Data\Database.mdf;Integrated Security=True;User Instance=True");
   
    public void ProcessRequest (HttpContext context) {
       // context.Response.ContentType = "text/plain";
       // context.Response.Write("Hello World");
        SqlCommand cmd = new SqlCommand("select EmpPic from Tbl_Emp where EmpID=@EmpID",con);
        if (con.State == ConnectionState.Closed)
        {
            con.Open();
        }
        cmd.Parameters.AddWithValue("@EmpID", context.Request.QueryString["EmpID"].ToString());
        SqlDataReader dr = cmd.ExecuteReader();

        if (dr.HasRows && dr.Read())
        {
            context.Response.BinaryWrite((byte[])(dr["EmpPic"]));
        }
      
        con.Close();
       
    }

    public bool IsReusable {
        get {
            return false;
        }
    }

}



I hope this article was useful 

You can download complete code from this  link Download Code

in next i am going to show how you can display all images in GridView Display Images in GridVIew


Comments

  1. great artical...thank u very much .finally my problem solved...

    ReplyDelete
  2. I m getting Instance failure error??
    hw can remove..it;
    in line
    con.open()

    ReplyDelete
    Replies
    1. hello

      Deepak

      Try this steps

      1. Stop all user instance processes of SQL Server running under your local account (open up task manager and look for sqlsrv.exe process and end it)

      2. Delete all files in the %LOCALAPPDATA%\Microsoft\Microsoft SQL Server Data\SQLEXPRESS folder

      3. F5 again

      and chnage connection string

      private static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");

      Delete
  3. Thnxx Manish for reply and i also caught error..i completed it using web.config file. Thnxx for this important artical.

    ReplyDelete
  4. Hi,

    I've got to save file that is choosen using fileupload control to the ms sql database (tbl_Material with columns as name, path, workshopTile FK).

    also the file choosen should only be in the zip format.

    what should be the code in c#. I want to use the strongly typed datasets.

    Please help as I'm a beginner in learning asp.net

    ReplyDelete
    Replies
    1. hey
      if(FileUploadControl.PostedFile.ContentType == "zip")
      {
      // write your file uploading code here
      }
      you can refer this link

      http://asp.net-tutorials.com/controls/file-upload-control/

      Delete
    2. Hi manish,
      Thanks for your reply. Can I have the code for storing those files via strongly typed datasets?

      Delete
  5. image is not appearing what is the reason for it ?? pls help

    ReplyDelete
    Replies
    1. if you have downloaded the same sample update you connection string with this

      static SqlConnection con = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True");

      Delete
    2. bvcvm,n.m

      Delete
  6. my image is not showing, though i have the correct data source anf provider written correctly. i am using access database but the image is not showing and there was no error, pls help me

    ReplyDelete
  7. Very thanks,,I got the solution from you

    ReplyDelete
  8. hi ,manish,,

    i have a error that is --"create instance for new object" on int position...plz..help me

    ReplyDelete
  9. JQuery Validation in ASP.NET Master Page

    http://allittechnologies.blogspot.in/2015/04/how-to-validate-aspnet-master-page-control-using-jquery.html

    ReplyDelete
  10. thanks it works well god bless your days man

    ReplyDelete
  11. Save and Retrieve image from Database and Display in Gridview or list of image in Panel
    Save and Retrieve Image from Database and Display in Gridview or Panel

    ReplyDelete
  12. i saved my image in folder of solution explorer with userid,now i want to show each image with user in gridview, how i can show. Please reply me . My email id is mukeshkamboj28@gmail.com

    ReplyDelete
  13. I love the blog. Great post. It is very true, people must learn how to learn before they can learn. lol i know it sounds funny but its very true. . .
    java training in marathahalli | java training in btm layout

    java training in jayanagar | java training in electronic city

    java training in chennai | java training in USA

    selenium training in chennai

    ReplyDelete
  14. I have been meaning to write something like this on my website and you have given me an idea. Cheers.
    python training in tambaram
    python training in annanagar
    python training in OMR
    python training in chennai

    ReplyDelete
  15. A very nice guide. I will definitely follow these tips. Thank you for sharing such detailed article. I am learning a lot from you.
    Blueprism training in annanagar

    Blueprism training in velachery

    Blueprism training in marathahalli

    ReplyDelete
  16. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.

    angularjs Training

    in chennai

    angularjs Training in chennai

    angularjs-Training in tambaram

    angularjs-Training in sholinganallur

    angularjs-Training in velachery

    ReplyDelete
  17. Excellent post!!!. The strategy you have posted on this technology helped me to get into the next level and had lot of information in it.
    Sap Mm Training From India

    ReplyDelete
  18. I am really happy with your blog because your article is very unique and powerful for new reader.
    Click here:
    selenium training in chennai
    selenium training in bangalore
    selenium training in Pune
    selenium training in pune
    Selenium Online Training


    https://skdotnetdeveloper.blogspot.com/2011/09/send-sms-in-cnet.html

    ReplyDelete
  19. A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  20. Wonderful Blog post, great article that you have provided for peoples. Its really good. Nice information.

    Data Science Courses in Bangalore

    ReplyDelete
  21. Awesome blog. I enjoyed reading your articles. This is truly a great read for me. I have bookmarked it and I am looking forward to reading new articles. Keep up the good work!
    date analytics certification training courses
    data science courses training

    ReplyDelete
  22. This website and I conceive this internet site is really informative ! Keep on putting up!
    Data Science Course in Pune

    ReplyDelete



  23. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.
    www.technewworld.in
    How to Start A blog 2019
    Eid AL ADHA

    ReplyDelete

  24. Great post i must say and thanks for the information. Education is definitely a sticky subject. it is still among the leading topics of our time. I appreciate your post and looking for more.Data Science Courses

    ReplyDelete
  25. Great tips and very easy to understand. This will definitely be very useful for me when I get a chance to start my blog.
    ir 4.0 training in malaysia

    ReplyDelete
  26. It’s great blog to come across a every once in a while that isn’t the same out of date rehashed material. Fantastic read.Automation Anywhere Training in Bangalore

    ReplyDelete
  27. Set your career with nearlearn’s data science training in Bangalore. This professional course will help you to understand each and all concepts of data science. Training available as online, classroom and corporate training in areas like BTM Layout, Indiranagar, Marathahalli, Koramangala, Jayanagar, and JP Nagar. We provide 100% placement assistance.

    data science with Python Classroom Training in Bangalore

    ReplyDelete

  28. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspired me to read more. keep it up.
    Correlation vs Covariance

    ReplyDelete
  29. Very interesting to read this article.I would like to thank you for the efforts you had made for writing this awesome article. This article inspried me to read more. keep it up.thanks a lot.
    Ai & Artificial Intelligence Course in Chennai
    PHP Training in Chennai
    Ethical Hacking Course in Chennai Blue Prism Training in Chennai
    UiPath Training in Chennai

    ReplyDelete
  30. This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information.
    Great post! Thanks for sharing this amazing post
    Artificial Intelligence Training in Hyderabad
    Artificial Intelligence Course in Hyderabad

    ReplyDelete
  31. This is my first time i visit here. I found so many entertaining stuff in your blog, especially its discussion. From the tons of comments on your articles, I guess I am not the only one having all the leisure here! Keep up the good work. I have been meaning to write something like this on my website and you have given me an idea.
    data scientists training

    ReplyDelete
  32. Nice post, thanks for sharing. Also check out the link of the given website
    Ambeone DMCC

    ReplyDelete
  33. Really awesome blog. Useful information and knowledgeable. Thanks for posting this blog. Keep sharing more blogs again soon.
    Data Science Training and Placements in Hyderabad

    ReplyDelete
  34. I can set up my new idea from this post. It gives in depth information. Thanks for this valuable information for all,..
    data analytics courses in hyderabad with placements

    ReplyDelete
  35. Your content is nothing short of brilliant in many ways. I think this is engaging and eye-opening material. Thank you so much for caring about your content and your readers. data analytics course in surat

    ReplyDelete

Post a Comment