Sunday, February 26, 2017

Save Image to Ms Sql using Asp .net

 Hi in this post I am going to show "How to save Image in MS SQL database using Asp.Net". Following steps are used to save image into sql server.

1.Find the Content Length of the Image.
2.Create a Byte Array .
3.Covert the image into stream and save it into byte array.

For this tutorial I am using the following sql structure for saving the image in database.

In the above the table id is the primary key column with auto increment.We use id column to fetch the image.

Html Tag:

<form id="form1" runat="server">
    <div>
        <h2>
            Upload Image to Database</h2>
        <hr />
        <strong>
            <asp:Label ID="lblImageLabel" runat="server" Text="Upload a Image:"></asp:Label></strong>
        <asp:FileUpload ID="fileUpload" runat="server" />
        <asp:Button ID="btnUpload" runat="server" Text="Upload Image" OnClick="btnUpload_Click" />
        <br />
        <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
        <hr />
        <h2>
            Retrive Image from Database</h2>
        <strong>
            <asp:Label ID="Label1" runat="server" Text="Image Id:"></asp:Label></strong>
        <asp:TextBox ID="txtImageId" runat="server"></asp:TextBox>
        <asp:Button ID="btnGetImage" runat="server" Text="Get image" OnClick="btnGetImage_Click" />
        <br />
        <div style="text-align:left;margin-top:10px;">
            <asp:Image ID="retrivedImage" runat="server" Height="250px" Width="250px" />
        </div>
    </div>
    </form>

Code for saving Image into database:

protected void btnUpload_Click(object sender, EventArgs e)
    {
        if (fileUpload.HasFile)
        {
            int iLen = fileUpload.PostedFile.ContentLength;
            byte[] image = new byte[iLen];

            fileUpload.PostedFile.InputStream.Read(image, 0, iLen);
            string constr = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
            SqlConnection conn = new SqlConnection(constr);
            string sqlQuery = "INSERT INTO tblImageDemo Values(@Image)";
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = sqlQuery;
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            //Command Parameters
            cmd.Parameters.AddWithValue("@Image", image);
            conn.Open();
            cmd.ExecuteNonQuery();
            lblStatus.Text = "File Uploaded Successfully...";
            lblStatus.ForeColor = System.Drawing.Color.Green;
            conn.Close();
        }
        else
        {
            lblStatus.Text = "Select a file to upload...";
            lblStatus.ForeColor = System.Drawing.Color.Red;
        }
    }
protected void btnGetImage_Click(object sender, EventArgs e)
    {
        retrivedImage.ImageUrl = "ImageHandler.ashx?Id=" + txtImageId.Text;
    }


To retrieve a Image we user Generic Handler:

To create a new Handler Right Click on the Project Click on the Generic Handler and name it as you like for the tutorial I named it has image handler.

public void ProcessRequest(HttpContext context)
    {
        string id = context.Request.QueryString["Id"];
        string constr = System.Configuration.ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        SqlConnection conn = new SqlConnection(constr);
        string sqlQuery = "SELECT Image FROM tblImageDemo WHERE Id=@Id";
        SqlCommand cmd = new SqlCommand();
   
        cmd.CommandText = sqlQuery;
        cmd.CommandType = System.Data.CommandType.Text;
        cmd.Connection = conn;
        conn.Open();
        cmd.Parameters.AddWithValue("@Id", id);
        SqlDataReader rdr = cmd.ExecuteReader();
        rdr.Read();
        context.Response.BinaryWrite((Byte[])rdr[0]);
        conn.Close();
        context.Response.End();
   
    }


Output:





Download Source Code


No comments:

Post a Comment