Upload images to database and View in Gridview

Sathya4260
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 10348 red flag
Rating: 5 out of 5  
 1 vote(s)

Most of them using the images to be displayed in their websites, I have most of the beginners when trying this they are able to upload the images to database but suffer a lot to view the same image in the web, Since i have posted the coding in C# to upload the image in database and view the list of all images in grid view.
Most of them using the images to be displayed in their websites, I have most of the beginners when trying this they are able to upload the images to database but suffer a lot to view the same image in the web, Since i have posted the coding in C# to upload the image in database and view the list of all images in grid view.

Here the coding starts,

First create the table as fallows,

create table filees(
id IDENTITY(1,1),
name varchar(50),
images image)


Let create the .aspx file the code as fallows, I used file upload control to upload the image,

    <form id="form1" runat="server">
        <asp:FileUpload ID="FileUpload1" runat="server" />
        <asp:Button runat="server" ID="btnSave" OnClick="SaveToTheDatabase" Text="Save to the database" />

<p><asp:Label ID="lblMessage" runat="server" EnableViewState="false" />&nbsp;</p>

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
    <asp:BoundField HeaderText="ID" DataField="id" />
    <asp:BoundField HeaderText="Picture Name" DataField="names" />
    <asp:TemplateField HeaderText="Picture">
    <ItemTemplate>
    <img src="Handler1.ashx?id=<%# Eval("id").ToString() %>" width="150" height="100" />
    </ItemTemplate>
    </asp:TemplateField>
</Columns>
</asp:GridView> 
</form>


When you select the image and cliks the button the image is saved in binary format.
The code behind coding is
protected void Page_Load(object sender, EventArgs e)
        {
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            DataTable table = new DataTable();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "SELECT id, names FROM files ORDER BY names";
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    using (SqlDataAdapter ad = new SqlDataAdapter(cmd))
                    {
                        conn.Open();
                        ad.Fill(table);
                        conn.Close();
                    }
                }
            }
            GridView1.DataSource = table;
            GridView1.DataBind();
        }

        protected void SaveToTheDatabase(object sender, EventArgs e)
        {
            string fileName = FileUpload1.PostedFile.FileName;
            int fileLength = FileUpload1.PostedFile.ContentLength;
            byte[] imageBytes = new byte[fileLength];
            FileUpload1.PostedFile.InputStream.Read(imageBytes, 0, fileLength);
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                string sql = "INSERT INTO files (names, doc) VALUES (@names, @doc)";
                SqlParameter[] prms = new SqlParameter[2];
                prms[0] = new SqlParameter("@names", SqlDbType.VarChar, 50);
                prms[0].Value = fileName;
                prms[1] = new SqlParameter("@doc", SqlDbType.Image);
                prms[1].Value = imageBytes;
                using (SqlCommand cmd = new SqlCommand(sql, conn))
                {
                    cmd.Parameters.AddRange(prms);
                    conn.Open();
                    cmd.ExecuteNonQuery();
                    conn.Close();
                }
                lblMessage.Text = "Picture uploaded successsfully !";
            }
        } 

And I am using the generic handler to view the images in the gridview, which is called by the item template in the gridview:

public void ProcessRequest(HttpContext context)
        {
            if (context.Request.QueryString["id"] == null) return;
            string connStr = ConfigurationManager.ConnectionStrings["setting"].ConnectionString;
            string pictureId = context.Request.QueryString["id"];
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                using (SqlCommand cmd = new SqlCommand("SELECT doc FROm files WHERE id = @id", conn))
                {
                    cmd.Parameters.Add(new SqlParameter("@id", pictureId));
                    conn.Open();
                    using (SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                       reader.Read();
                        context.Response.BinaryWrite((Byte[])reader[reader.GetOrdinal("doc")]);
                        reader.Close();
                    }
                }
            }
        }
        public bool IsReusable
        {
            get
            {
                return true;
            }
        } 

Usually the IsReusable is set to false, I changed so that the same handler can be used in future.

Hope this will be helpful. Thanks
Page copy protected against web site content infringement by Copyscape

About the Author

Sathya4260
Full Name: sathish kumar
Member Level:
Member Status: Member
Member Since: 12/17/2010 7:34:35 AM
Country: India
Sathish Kumar S

GNIIT Software Engineer, MCPD web Developer, MCTS .Net Framework and Sql server certified

Login to vote for this post.

Comments or Responses

Posted by: Prabhakar on: 1/24/2011 | Points: 25
hi sathya

gud article images to database and View in Gridview. it's a very use full

Thanks & regard's
Prabhakar
Posted by: Seenuvasan on: 9/14/2011 | Points: 25
Hi sathya,

you missed datatype of ID in create table query. pls correct this one.
And article is very good. keep it up.

Login to post response

Comment using Facebook(Author doesn't get notification)