Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

How to Validate FileUpload on Serverside with Specific Files Extensions

0.00/5 (No votes)
31 May 2014CPOL 13.3K  
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.NET
<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

C#
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;
            }
        }
    }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)