How to display preview of image before upload?
In this article I have explained about how to show preview of an image before that image upload to Server. This example I have used one file upload control for collecting files and store it into SQL Server database table. The image is store in the “Image” data type field.
How to show preview of image?
I am convert image fiels into byte array values then store it in the session value. Access that session value in Default2.aspx value bind it as image in Image control. This image control shows preview now.
if (FileUpload1.HasFile)
{
dt.Clear();
postfile1 = pstFile(FileUpload1);
Session["b"] = postfile1;
dr = dt.NewRow();
dt.Columns.Add("sname");
dt.Columns.Add("simage",Type.GetType("System.Byte[]"));
dr["sname"] = TextBox1.Text;
dr["simage"] = postfile1;
dt.Rows.Add(dr);
Session["dt"]=dt;
Image1.ImageUrl="Default2.aspx";
Button1.Enabled = false;
Button2.Enabled = true;
}
How to upload preview image in to sql server database?
After user saw preview then he/she want to upload file that time I have insert that session value into the table. Otherwise if he click cancel button clear images in image control.
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["b"] != null)
{
sqlcon.Open();
query = "insert into stud(sname,simage) values(@sname,@simage)";
SqlCommand cmd = new SqlCommand(query, sqlcon);
cmd.Parameters.Add("@sname", SqlDbType.VarChar).Value = TextBox1.Text;
cmd.Parameters.Add("@simage", SqlDbType.Image).Value = ((byte[])Session["b"]);
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
sqlcon.Close();
TextBox1.Text = "";
Image1.ImageUrl = "";
Label1.Text = "Image Uploaded Successfully";
Button1.Enabled = true;
Button2.Enabled = false;
Session.Remove("b");
}
}
Source Code Detail:
Here with I have attached source code for display image as preview from file upload control. Down load it and try to check preview of an image before upload.
Front End : ASP.NET
Code Behind : C#
Output
Conclusion:
I hope this article is help to show preview of an image before upload.
Thanks for the post, it's working perfectly!!!