Wednesday, 20 July 2011

Restrict FileUpload Extensions with ASP.NET 4.0 and C#


This tutorial will demonstrate how to apply client side and server side filters on the file upload control using ASP.NET 4.0 and C#.

Adding the Default.aspx Page
To demonstrate how we can add client and server side validation to restrict file extensions to the file upload control, we will need a simple form. We will be using a file upload control, custom validator, and a button to cause post backs. At this point, I have created a new ASP.NET Empty Web Site. To begin:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
  6. Open Default.aspx up to design mode.
  7. Drag and drop a fileupload control onto the web form.
  8. Drag and drop a customvalidator next to the fileupload control.
  9. Change the ErrorMessage property to 'Please select a valid file type (*.jpg, *.jpeg).'
  10. Add a break line after the customvalidator.
  11. Add a button underneath the fileupload control.
Server Intellect assists companies of all sizes with their hosting needs by offering fully configured server solutions coupled with proactive server management services. Server Intellect specializes in providing complete internet-ready server solutions backed by their expert 24/365 proactive support team.

Adding Client Side Validation
Because we cannot limit the file types that are viewed in the file browser, we must go about some different methods to inform our user what the file upload control is expecting. In this example, we will create some validation to allow only '.jpg' and '.jpeg' file types. To do this client side, we must implement some simple javascript and associate it with our file upload control. To add in the javascript portion, open up Default.aspx and add the following script block into the <head> tag:
<script type="text/javascript">
    function checkFileExtension(elem)
    {
        var filePath = elem.value;

        if (filePath.indexOf('.') == -1)
            return false;

        var validExtensions = new Array();
        var ext = filePath.substring(filePath.lastIndexOf('.') + 1).toLowerCase();

        validExtensions[0] = 'jpg';
        validExtensions[1] = 'jpeg';

        for (var i = 0; i < validExtensions.length; i++)
        {
            if (ext == validExtensions[i])
                return true;
        }

        alert('The file extension ' + ext.toUpperCase() + ' is not allowed!');
        return false;
    }
</script>

Let's go over what this function actually does. First, it gets the extension from the currently selected file and then checks to see if it is valid. If it finds an invalid extension, it executes an alert popup that displays a message saying that the current file type is not allowed. Next, we need to create the association between our javascript function and file upload control. To do this, open Default.aspx.cs up for editing and add in the following code to the Page_Load event method:
protected void Page_Load(object sender, EventArgs e)
{
    //add our javascript function to the fileupload control
    FileUpload1.Attributes.Add("onchange""return checkFileExtension(this);");
}

I just signed up at Server Intellect and couldn't be more pleased with my fully scalable & redundant cloud hosting! Check it out and see for yourself.

Adding Server Side Validation
Next, we will add in some code that will cause validation on the server so that we can prevent the user from uploading invalid file types. To begin, open up Default.aspx to design mode and double click the customvalidator to generate the CustomValidator1_ServerValidate event method, then add the following code to that method:
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
    //create an array of valid file extensions
    string[] validExt = { "jpg""jpeg" };

    //set args to invalid
    args.IsValid = false;

    //get file name
    string fileName = FileUpload1.PostedFile.FileName;

    //check to make sure the string is not empty
    if (!String.IsNullOrEmpty(fileName))
    {
        //get file extension
        string fileExt = fileName.Substring(fileName.LastIndexOf('.') + 1).ToLower();
        //check if the current extension matches any valid extensions
        for (int i = 0; i < validExt.Length; i++)
        {
            if (fileExt == validExt[i]) //if we find a match
                args.IsValid = true;    //validate it
        }
    }
}

Let's go over what this code is doing. First, we setup the valid file extensions that we will be looking for. Then, we check the current file extension and see if it matches any of our valid extensions. If it does we validate it, if not the validation fails and the error message is displayed in our custom validator.

We used over 10 web hosting companies before we found Server Intellect. Our cloud hosting,was set up in less than 24 hours. We were able to confirm our order over the phone. They responded to our inquiries within an hour. Server Intellect's customer support and assistance are the best we've ever experienced.

Testing
To test this out:
  1. Load up the web site.
  2. Click browse.
  3. Select an invalid file type.
  4. Click open.
  5. Notice the popup that alerted you the file type was invalid.
  6. Click the button.
  7. Notice the error message from the custom validator being displayed.
  8. Click browse.
  9. Select a valid file type.
  10. Click open.
  11. Notice that there is no popup.
  12. Click the button.
  13. Notice there is no error message from the custom validator.
These are two effective methods of restricting file types with the file upload control. While both are effective, they are not both necessary as one can work without the other.

No comments:

Post a Comment