Wednesday, February 3, 2010

Upload Image in Database and Display Image

upload images.. first i created a database table with the following columns...

Id --> int (identity column, and primary key)

firstname -->varchar(50)

lastname -->varchar(50)

image -->varchar(50)

and under my web site root directory i have created a folder with name..(images)

here is the code.. to upload the image....



using System.IO;
using System.Data.SqlClient;
using System.Web.Configuration;

protected void Button1_Click(object sender, EventArgs e)
{
if (FileUpload1.HasFile)
{
string fileExt = Path.GetExtension(FileUpload1.FileName).ToLower();
string fileName = Path.GetFileName(FileUpload1.FileName);
string dbfilePath = @"~/images/" + fileName;
if (fileName != string.Empty)
{
try
{
if (fileExt == ".jpg" || fileExt == ".gif")
{
FileUpload1.SaveAs(Server.MapPath(@"~/images/") + fileName);
}
else
{
Response.Write("You can upload only JPG or GIF files...");
}
}
catch (Exception ex)
{
throw ex;
}
}
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into images values(@firstname,@lastname,@image)",con);
cmd.Parameters.AddWithValue("@firstname",TextBox1.Text);
cmd.Parameters.AddWithValue("@lastname",TextBox2.Text);
cmd.Parameters.AddWithValue("@image",dbfilePath);
con.Open();
int i = cmd.ExecuteNonQuery();
con.Close();
if (i > 0)
{
Response.Write("Uploaded");
}
}

}


Display Image in Repeater

his is how you can display the images in Repeater control....

Html...









CodeBehind...
using System.Data.SqlClient;
using System.Web.Configuration;

protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["myConnection"].ConnectionString);
SqlCommand cmd = new SqlCommand("select * from images",con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
Repeater1.DataSource = dt;
Repeater1.DataBind();
}

Regard
Prateek

No comments:

Post a Comment