This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

3 Dec 2012

Simple example for UPLOADING FILES IN ASP.NET

In this post we will see a small example to understand the file upload control in Asp.net. For this take a fileupload control,buttong controla and a label on form default.aspx, code given below..

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>

    </style>
</head>
<body>
    <form id="form1" runat="server">
    <p>
        <asp:FileUpload ID="FileUpload1" runat="server" />
    </p>
    <p>
        <asp:Label ID="lblContentType" runat="server"></asp:Label>
    </p>
    <p>
        <asp:Button ID="btnUpload" runat="server" onclick="btnUpload_Click" 
            Text="Upload" />
    </p>
    </form>
</body>
</html>


And Then a folder a new folder "uploads" to your website..   The c# code in the code behind file is like this:

using System;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        string path = Server.MapPath("." + "//uploads//" + FileUpload1.FileName);
        if (FileUpload1.HasFile)
        {
            lblContentType.Text = FileUpload1.PostedFile.ContentType;
            if (System.IO.File.Exists(path))
            {
                Response.Write("file already exists..");
            }
            else
            {
                FileUpload1.SaveAs(path);
                Response.Write("Upload successfull..");
            }
        }
    }
}


In the above code you can see Server.MapPath, here we are saving the uploaded file in uploads folder in our asp.net website.

You can see the image below to understand output,Here it is a screen shot when a ms word 2007 file is uploaded..

Download Sample Code : FileUploadControl.rar

No comments:

Post a Comment

Thanks for your comments.
-Sameer