December 20, 2010

Upload the image to database and View in Gridview

Hi,

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 the 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 grip view, which is called by the item template in the grip view:

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 method is set to false, i changed so that the same handler can be used in future.



The output would be show as:

1 comment:

  1. Sathya, I dont see any screenshots which you have posted.

    ReplyDelete