FileUploadExtender Class - ASP.NET

This page is part of the Class Library Pages collection.
Click the icon to see the index.

Features

This class extends the built-in <asp:FileUpload> web control as follows.


Example Implementation

To use this control, you need to follow the instructions in the Consuming Custom Controls in ASP.NET article.

ASPX Code

FileUploadExtender Control

<vzw:FileUploadExtender runat="server" ID="uxFileUpload" Width="98%" 
    RequiredField="false" 
    />

Validation Control

If you change the ID of the FileUploadExtender control, change the ID of this CustomValidator to follow this naming convention: the ID of the CustomValidator is the ID of the FileUpload control, plus "Validator".

<asp:CustomValidator runat="server" Text="" Display="Dynamic"
    SetFocusOnError="true" ValidationGroup="MainValidationGroup"
    EnableClientScript="false"
    OnServerValidate="uxFileUploadValidator_Validate"
    ID="uxFileUploadValidator"
    ErrorMessage="ERROR"
    >
    
    <asp:Image ID="Image6" runat="server" 
        ImageUrl="~/images/Exclamation.PNG" />
    
    </asp:CustomValidator>

Code-Behind

VB.NET

This code assumes the following naming convention: the ID of the CustomValidator is the ID of the FileUpload control, plus "Validator".

Protected Sub uxFileUploadValidator_Validate(ByVal sender As Object, ByVal e As ServerValidateEventArgs)

    Dim uxSender As CustomValidator = CType(sender, CustomValidator)
    Dim uploaderName As String = uxSender.ID.Replace("Validator", "")
    Dim c As Control = uxSender.Parent.FindControl(uploaderName)
    Dim uxFileUploadExtender As VZW.FileUploadExtender = CType(c, VZW.FileUploadExtender)

    e.IsValid = uxFileUploadExtender.IsValid
    uxSender.ErrorMessage = uxFileUploadExtender.Reason

    ' This next line compensates for an apparent bug with the CustomValidator control, wherein 
    ' upon a SECOND failed validation, its TEXT property is set to its ERRORMESSAGE property.
    uxSender.Text = "<img src='images/Exclamation.PNG' />"

End Sub

C#

protected void uxFileUploadValidator_Validate(object sender, ServerValidateEventArgs e)
{
    CustomValidator uxSender = (CustomValidator)sender;
    string uploaderName = uxSender.ID.Replace("Validator", "");
    Control c = uxSender.Parent.FindControl(uploaderName);
    FileUploadExtender uxFileUploadExtender = (FileUploadExtender)c;

    e.IsValid = uxFileUploadExtender.IsValid;
    uxSender.ErrorMessage = uxFileUploadExtender.Reason;

    /*  This next line compensates for an apparent bug with the CustomValidator control, wherein 
        *  upon a SECOND failed validation, its TEXT property is set to its ERRORMESSAGE property.
        */
    uxSender.Text = "<img src='images/Exclamation.PNG' />";
}




Source Code

VB.NET

Imports Microsoft.VisualBasic
Imports System.Web.UI.WebControls
Imports System.IO

Namespace AcmeBroomCompany

    Public Class FileUploadExtender

        Inherits FileUpload

        Private _reason As String
        Private _requiredField As Boolean

        Public Sub New()

            _requiredField = False
            _reason = ""

        End Sub

        Public Property RequiredField() As Boolean
            Get
                Return _requiredField
            End Get
            Set(ByVal value As Boolean)
                _requiredField = value
            End Set
        End Property

        Public ReadOnly Property IsValid() As Boolean
            Get
                Dim result As Boolean = False
                Dim validExtensions As String = ConfigurationManager.AppSettings("AllowedFileExtensions")
                _reason = ""

                If validExtensions Is Nothing Then

                    _reason = "No valid extensions for file uploads were found in the configuration file."

                ElseIf _requiredField And Not Me.HasFile Then

                    _reason = "File name is required."

                ElseIf Me.HasFile Then

                    Dim exts() As String = validExtensions.Split(New Char() {"|"c}, _
                                                StringSplitOptions.RemoveEmptyEntries)

                    Dim myExt As String = Path.GetExtension(Me.FileName).ToUpper()
                    If myExt.Length > 0 Then
                        myExt = myExt.Substring(1)
                    End If

                    _reason = "You are not allowed to upload files with a '." + myExt + "' extension"

                    For Each ext As String In exts

                        If myExt = ext.ToUpper() Then
                            result = True
                            _reason = ""
                        End If

                    Next

                Else

                    result = True

                End If

                Return result

            End Get
        End Property
        Public ReadOnly Property Reason() As String
            Get
                Return _reason
            End Get
        End Property

        ''' <summary>
        ''' Maps the virtual path to a physical path on the server, creates the folder (if necessary), 
        ''' and uploads the specified file to this folder.
        ''' </summary>
        Public Sub SaveTo(ByVal virtualPath As String)

            If Me.HasFile AndAlso Me.IsValid Then

                Dim shortFileName As String = Me.FileName
                Dim serverPath As String = Me.Page.Server.MapPath(virtualPath)

                If Not Directory.Exists(serverPath) Then
                    Directory.CreateDirectory(serverPath)
                End If

                Dim serverFile As String = Path.Combine(serverPath, shortFileName)

                Me.SaveAs(serverFile)

            End If

        End Sub

    End Class

End Namespace

C#

using System;
using System.Configuration;
using System.IO;

namespace AcmeBroomCompany
{
    public class FileUploadExtender : System.Web.UI.WebControls.FileUpload
    {
        private string _reason;
        private bool _requiredField;

        public FileUploadExtender()
        {
            _requiredField = false;
            _reason = "";
        }
        public bool RequiredField
        {
            get { return _requiredField; }
            set { _requiredField = value; }
        }
        public bool IsValid
        {
            get
            {
                bool result = false;

                string validExtensions = ConfigurationManager.AppSettings["AllowedFileExtensions"];
                _reason = "";

                if (validExtensions == null || validExtensions.Length == 0)

                    _reason = "No valid extensions for file uploads found in the configuration file.";

                else if (_requiredField & !this.HasFile)

                    _reason = "File name is required.";

                else if (this.HasFile)
                {
                    string[] exts = validExtensions.Split(new char[] {'|'},  
                        StringSplitOptions.RemoveEmptyEntries);

                    string myExt = Path.GetExtension(this.FileName).ToUpper();
                    if (myExt.Length > 0)
                        myExt = myExt.Substring(1);

                    _reason = "You are not allowed to upload files with a '." + myExt + 
                        "' extension.";

                    foreach (string ext in exts)
                    {
                        if (myExt == ext.ToUpper())
                        {
                            result = true;
                            _reason = "";
                            break;
                        }
                    }
                }
                else

                    result = true;

                return result;
            }
        }
        public string Reason
        {
            get { return _reason; }
        }

        public void SaveTo(string virtualPath)
        {
            if (this.HasFile && this.IsValid)
            {
                string shortFileName = this.FileName;
                string serverPath = this.Page.Server.MapPath(virtualPath);

                if (!Directory.Exists(serverPath))
                    Directory.CreateDirectory(serverPath);

                string serverFile = Path.Combine(serverPath, shortFileName);

                this.SaveAs(serverFile);
            }
        }
    }
}