65.9K
CodeProject is changing. Read more.
Home

How to Validate FileUpload on Serverside with Specific Files Extensions

May 31, 2014

CPOL
viewsIcon

13282

Validate Fileupload using server side custom Validation

Introduction

In this tip, I will show you how to use Custom Validator to validate fileupload on server side in ASP.NET. In this, we ensure that the file upload is of only Image type, not other like video or documents.

The Code

STEP 1: Create a Fileupload on your Webpage wherever you want.

STEP 2: Create a Requiredfieldvalidator and Custom Validator set Controltovalidate and Errormessage properties of Requiredfieldvalidator and Custom Validator.

Fuvalidate.aspx

<asp:FileUpload ID="fu1" runat="server" /><br />
<br />
<asp:Button ID="Button1" runat="server" Text="Upload File" />&nbsp;<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
        
<asp:CustomValidator ID="cvfu1" runat="server" ErrorMessage="Only .jpeg files allowed!" 
ControlToValidate="fu1" onservervalidate="cvfu1_ServerValidate"  ></asp:CustomValidator>
<br />
<asp:RequiredFieldValidator  id="rvfu1" 
runat="server"  ErrorMessage="This is a required field!"  
ControlToValidate="fu1"></asp:RequiredFieldValidator>

// Any source code blocks look like this
//

Fuvalidate.aspx.cx

protected void cvfu1_ServerValidate(object source, ServerValidateEventArgs args)
    {
        String fileName = fu1.PostedFile.FileName;
        if (fu1.HasFile)
        {
            string fileExt = System.IO.Path.GetExtension(fu1.FileName);

        if (fileExt.ToLower() == ".jpeg" || fileExt.ToLower() == ".jpg" || 
            fileExt.ToLower() == ".gif" || fileExt.ToLower() == ".png" || 
            fileExt.ToLower() == ".bitmap")
            {
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }
        }
    }