Validating Image File for Content Type with ASP.NET FileUpload web control.

We use file upload web control in our sites, where we want only valid image types to be uploaded.

Without talking much -> here are 3 ways to do it.

1. Accept attribute of fileUpload control - Doesnt work with most of the browsers (Bad with IE itself)

2. Regular Expression validator for FileUpload

<asp:RegularExpressionValidator id="UpLoadValidator" runat="server" ErrorMessage="Upload Images only." ValidationExpression="^(([a-zA-Z]:)|( \\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.png|.bmp|.jpeg|.gif)$ " ControlToValidate="FileUpload1"> </asp:RegularExpressionValidator>

This is Not very handy when using AJAX controls on page- Both javascripts dont like each other :)

3. Write a code behind function in a very simple way - Most robust way to use it. - Very Generic can be used for any file types.

private bool IsFileValid()

{

string [] allowedImageTyps = {"image/gif", "image/pjpeg", "image/bmp","image/x-png"};

StringCollection imageTypes = new StringCollection();

imageTypes.AddRange(allowedImageTyps);

if (imageTypes.Contains(FileUpload1.PostedFile.ContentType))

return true;

else

{

return false;

}

}

 NOTE - use FileUpload1.PostedFile.ContentType and not the file name to check the Extension

Leave a comment if this helped you

Comments

  • Anonymous
    November 05, 2009
    Thanks a lot.Its working greatly.Why its not working with ajax??