ASP.NET’s Image Upload Filetype Validation

Posted by William on Apr 27, 2009

ASP.NET’s file upload facility offers a quick, easy method for allowing users to upload content to your server. In many cases however the upload type must be restricted. For example, perhaps you are allowing users to upload a profile image. You certainly don’t want them to be capable of uploading an executable (.exe) file!

The simple solution is to attach a RegularExpressionValidator to the file upload control.  Below is an example of a RegularExpressionValidator restricting the accepted filetypes of a FileUpload control to .gif, .jpg, .jpeg or .png.

1
2
<asp:FileUpload ID="uplImage" runat="server" />
<asp:RegularExpressionValidator ID="revImage" ControlToValidate="uplImage" ValidationExpression="^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$" Text=" ! Invalid image type" runat="server" />

Here is the regular expression on it’s own.

1
^.*\.((j|J)(p|P)(e|E)?(g|G)|(g|G)(i|I)(f|F)|(p|P)(n|N)(g|G))$

Unfortunately we cannot simply ignore case in the expression. The RegularExpressionValidator does not have an option to ignore case and the ASP.NET Regex Engine’s ignore case construct is not supported on the client side Javascript Regex Engine. However, the expression above will match all variations of upper/lowercase characters such as .gif, .GIF and .Gif

One small gotcha, don’t forget to check in your postback handler that the page is valid! If you do forget and the regular expression match fails, your code will still execute.

1
2
3
4
5
6
7
protected void btnUpload_Click(object sender, EventArgs e)
{
        if (IsValid)
        {
                // Process your data
        }
}