In this article I will explain how to validate (check) File Size in KB, Dimensions (Height and Width) of an Image using CustomValidator in ASP.Net using C# and VB.Net.
HTML Markup
The HTML Markup consists of a FileUpload control, a Button and a CustomValidator for which an OnServerValidate event has been specified.
<asp:FileUpload ID="FileUpload1" runat="server" />
<asp:Button ID="btnUpload" Text="Upload" runat="server" /><br />
<asp:CustomValidator ID="CustomValidator1" OnServerValidate="ValidateFileSize" ForeColor="Red" runat="server" />
Validating File Size, Dimensions (Height and Width) of an Image using CustomValidator in ASP.Net
When the Upload button is clicked, the OnServerValidate event handler of the CustomValidator is executed.
Here first the uploaded Image file is read into an Image object and its dimensions i.e. Height and Width are determined.
Then using the ContentLength property of the PostedFile, the size of the File is calculated in Kilobytes (KB).
Now the size is compared with the threshold value and if the value exceeds, the isValid argument is set to false and appropriate error message is set in the Custom Validator.
C#
protected void ValidateFileSize(object sender, ServerValidateEventArgs e)
{
System.Drawing.Image img = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
int height = img.Height;
int width = img.Width;
decimal size = Math.Round(((decimal)FileUpload1.PostedFile.ContentLength / (decimal)1024), 2);
if(size > 100)
{
CustomValidator1.ErrorMessage = "File size must not exceed 100 KB.";
e.IsValid = false;
}
if (height > 100 || width > 100)
{
CustomValidator1.ErrorMessage = "Height and Width must not exceed 100px.";
e.IsValid = false;
}
}
VB.Net
Protected Sub ValidateFileSize(sender As Object, e As ServerValidateEventArgs)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream)
Dim height As Integer = img.Height
Dim width As Integer = img.Width
Dim size As Decimal = Math.Round((CDec(FileUpload1.PostedFile.ContentLength) / CDec(1024)), 2)
If size > 100 Then
CustomValidator1.ErrorMessage = "File size must not exceed 100 KB."
e.IsValid = False
End If
If height > 100 OrElse width > 100 Then
CustomValidator1.ErrorMessage = "Height and Width must not exceed 100px."
e.IsValid = False
End If
End Sub
Screenshot
Error message shown when the File size exceeds the threshold limit
Error message shown when the file dimensions (Height or Width) exceeds the threshold limit
Demo
Downloads
Download Code