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 :)
<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.
{
imageTypes.AddRange(allowedImageTyps);
}
NOTE - use FileUpload1.PostedFile.ContentType and not the file name to check the Extension
Leave a comment if this helped you