asp.net c# tutorials and examples code for web developers

Thursday, October 9, 2008

ASP.NET FileUpload Control Example

FileUpload Control Example

FileUpload control is a Standard ToolBox control. Here I show a simple use of FileUpload control.

Simple Use
First create a folder name UploadFolder in your computer C:\ Drive. Then create a Web Form name FileUpload.aspx. FileUpload.aspx page code is here.

<%@ Page Language="C#" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">
    protected void Button1_Click(object sender, System.EventArgs e) {
        if (FileUpload1.HasFile)
        {
            try
            {
                FileUpload1.SaveAs("C:\\UploadFolder\\" + FileUpload1.FileName);
                Label1.Text = "Uploaded File: " + FileUpload1.PostedFile.FileName +
                    "<br /> File Size: " + FileUpload1.PostedFile.ContentLength;
            }
            catch (Exception ex)
            {
                Label1.Text = "An Error occured: "+ ex.Message.ToString();
            }
        }
           
        else
        {
            Label1.Text = "First choose an file then click button";
        }
        
    }
</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>FileUpload Control Example</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Label ID="Label1" runat="server" Font-Size="X-Large" ForeColor="Crimson" ></asp:Label>
        <hr />
        <asp:FileUpload ID="FileUpload1" runat="server" BackColor="Chocolate" />
        <asp:Button ID="Button1" runat="server" Text="Upload the selected file" OnClick="Button1_Click" />
    </div>
    </form>
</body>
</html>












Related asp.net examples