Tuesday 8 January 2013

Image upload code in c# | asp.net image file uploading in database | gridview


How to upload images in asp.net using c#

string path = Server.MapPath("Images/"); //Images is folder here it will show full path where file or pic is going to store//

lblMessage.Text = path;

if (FileUpload1.HasFile)

{

string Filext = Path.GetExtension(FileUpload1.FileName);

if(Filext==".jpg" || Filext==".png")

{
 HttpPostedFile myFile = FileUpload1.PostedFile;
                int nFileLen = (myFile.ContentLength)/1000; // will check file length
FileUpload1.SaveAs(path+ FileUpload1.FileName);
string filnm="~/Images/"+FileUpload1.FileName;
string nm = txtName.Text.Trim();
string filenm = filnm.ToString();
string query="insert into images (ImageName,Image)values (@imgnm,@imgpath)";
SqlCommand cmd=new SqlCommand(query,con);
cmd.Parameters.AddWithValue("@imgnm", nm);
cmd.Parameters.AddWithValue("@imgpath", filenm);
SqlCommand disply = new SqlCommand("select * from images", con);
SqlDataAdapter da = new SqlDataAdapter(disply);
DataTable dt = new DataTable();
da.Fill(dt);
grdvw.DataSource = dt;
grdvw.DataBind();
con.Open();
int i = 0;
i= cmd.ExecuteNonQuery();
if(i>0)
{
lblMessage.Text="Image uploaded succesfully";
}
else
{
lblMessage.Text="Please select the image";
}
}
else
{
lblMessage.Text="please selest .png or .jpg files only";
} } }



<asp:fileupload id="FileUpload1" runat="server">
<asp:button id="btnupload1" onclick="btnupload1_Click" runat="server" text="Upload">

<asp:textbox id="txtName" runat="server" width="95px">

</asp:textbox>
<asp:label id="lblMessage" runat="server"></asp:label>
<asp:gridview autogeneratecolumns="false" id="grdvw" runat="server">
<columns>
<asp:boundfield datafield="ID" headertext="Number">
<asp:boundfield datafield="ImageName" headertext="Product">
<asp:imagefield controlstyle-height="120px" controlstyle-width="120px" dataimageurlfield="Image" headertext="Image">
</asp:imagefield>
</asp:boundfield></asp:boundfield></columns>
</asp:gridview></asp:button></asp:fileupload></div>