Search
Author
ASP.NET Tutorials
Author
Sheo Narayan
Advertisements


Winners

Win Prizes

Social Presence
Twitter Twitter LinkedIn YouTube Google

Like us on Facebook

Silverlight Tutorials | Report a Bug in the Tutorial
Share this to:

Bookmark It
asp:FileUpload control
FileUpload control allows users to upload file to the webserver.
 
FileUpload control allows users to upload file to the server. When it is rendered on the page, it is implemented through <input type=file /> HTML tag. Its properties like BackColor, ForeColor, BorderColor, BorderStyle, BorderWidth, Height etc. are implemented through style properites of <input>.
DEMO : FileUpload Show Source Code
              // File upload control
              <asp:FileUpload ID="FileUpload2" runat="Server" />
              
    // Fires when Button is clicked.
    protected void UploadFileOnServer(object sender, EventArgs e)
    {
        // limitation of maximum file size
        int intFileSizeLimit = 10;

        // get the full path of your computer
        string strFileNameWithPath = FileUpload1.PostedFile.FileName;
        // get the extension name of the file
        string strExtensionName = System.IO.Path.GetExtension(strFileNameWithPath);
        // get the filename of user file
        string strFileName = System.IO.Path.GetFileName(strFileNameWithPath);
        // get the file size
        int intFileSize = FileUpload1.PostedFile.ContentLength / 1024; // convert into byte

        // Restrict the user to upload only .gif or .jpg file
        strExtensionName = strExtensionName.ToLower();
        if (strExtensionName.Equals(".jpg") || strExtensionName.Equals(".gif"))
        {
            // Rstrict the File Size 
            if (intFileSize < intFileSizeLimit)
            {
                // upload the file on the server
                // you can save the file with any name, However as this is the sample so I have saved the file same name for all users. So it will overwrite your file with next user's who will test this tutorials.
                FileUpload1.PostedFile.SaveAs(Server.MapPath("~/UserFiles/Samples/") + "SampeFromTutorials" + strExtensionName);

                lblMessage.Text = "Uploaded file details <hr />" +
                    "File path on your Computer: " + strFileNameWithPath + "<br />" +
                    "File Name: " + strFileName + "<br />" +
                    "File Extension Name: " + strExtensionName + "<br />" +
                    "File Size: " + intFileSize.ToString();
            }
            else
            {
                lblMessage.Text = "File size exceeded than limit " + intFileSizeLimit + " KB, Please upload smaller file.";
            }
        }
        else
        {
            lblMessage.Text = "Only .jpg or .gif file are allowed, try again!";
            lblMessage.ForeColor = System.Drawing.Color.Red;
        }
    }