Search This Blog

Tuesday, February 14, 2012 Saving Image in binary into database table in Sql 2005/2008

In this article, I am going to explain how to store image file in database. for this I am using Northwind database and product table.
In this implementation, I have added a  column ProductImage of image datatype for storing the image of each product.

ALTER TABLE Products ADD ProductImage IMAGE

Html Code in aspx part
The code is very simple - the web page contains a text box for getting the Product Id of the record and a file upload control in the page and A button. 

       Save Image in Database
            <td style="vertical-align:top">Product ID</td>
            <td><asp:TextBox ID="txtProductID" runat="server" Width="100px"></asp:TextBox></td>
            <td><asp:FileUpload runat="server" ID="fuImage" Width="400px" /> </td>
            <td colspan="2" style="text-align:center">
                <asp:Button ID="btnSave" runat="server" Width="80px" Text="Save"
                    onclick="btnSave_Click" />
On click of Save button on the page, below code executed
protected void btnSave_Click(object sender, EventArgs e)
            if ((fuImage.PostedFile.FileName.Trim().Length > 0) &&
                (fuImage.PostedFile != null))
                byte[] image = new byte[fuImage.PostedFile.ContentLength];

                fuImage.PostedFile.InputStream.Read(image, 0, (int)fuImage.PostedFile.ContentLength);

                SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString);

                SqlCommand command = new SqlCommand();
                command.CommandText = "Update Products set ProductImage = @Image where ProductID = '" + txtProductID.Text + "'";

                command.CommandType = CommandType.Text;
                command.Connection = connection;

                PrepareSQLParameter(command, "@Image", SqlDbType.Image, image.Length, image);


                int result = command.ExecuteNonQuery();

                txtProductID.Text = "";


        private SqlParameter  PrepareSQLParameter(SqlCommand command, string parameterName, SqlDbType parameterType, int parameterLength, object parameterValue)
            SqlParameter parameter = new SqlParameter(parameterName, parameterType, parameterLength);
            parameter.Value = parameterValue;

            return parameter;

No comments :

Post a Comment