Popular Posts

Monday, 11 July 2011

Insert Image into Database ASP.Net

Here we provide a simple process for uploading image and save it into SQL table. Step by step all processes are describe below.


Step 1 : Create a form on asp.net look like below;

HTML Coding for Creating form:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtImageName" runat="server" Width="110px"> </asp:TextBox>

<asp:FileUpload ID="FileUpload1" runat="server"/>

<asp:Button ID="btnUpload" runat="server"
            OnClick="btnUpload_Click" Text="Upload"/>
</div>
</form>
Step 2:  Now Create Database with 3 fields like ImageID, ImageName, Image.

Step 3: Write a Click event of Upload button in .cs Class.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;

protected void btnUpload_Click(object sender, EventArgs e)
    {
        string strImageName = txtImageName.Text.ToString();
        if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != "")
        {
        byte[] imageSize = new byte [FileUpload1.PostedFile.ContentLength];
        HttpPostedFile uploadedImage = FileUpload1.PostedFile;
        uploadedImage.InputStream.Read (imageSize, 0,          (int)FileUpload1.PostedFile.ContentLength);
            // Create SQL Connection
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings
             ["ConnectionString"].ConnectionString;
            // Create SQL Command
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "INSERT INTO InsertImageDemoTable(ImageName,Image)" +
            " VALUES (@ImageName,@Image)";
            cmd.CommandType = CommandType.Text;
            cmd.Connection = con;
            SqlParameter ImageName = new SqlParameter ("@ImageName", SqlDbType.VarChar, 50);
            ImageName.Value = strImageName.ToString();
            cmd.Parameters.Add(ImageName);
            SqlParameter UploadedImage = new SqlParameter
             ("@Image", SqlDbType.Image, imageSize.Length);
            UploadedImage.Value = imageSize;
            cmd.Parameters.Add(UploadedImage);
            con.Open();
            int result = cmd.ExecuteNonQuery();
            con.Close();
            GridView1.DataBind();
        }

    }

Note: You can see how fatch images from database and show in Gridview with following link ;
http://dotnetmatrix.blogspot.com/2011/07/fatch-image-in-gridview-from-database.html

No comments:

Post a Comment