How to restrict user to upload images of up to specified size in asp.net

Introduction:  In previous articles i explained  How to Validate and upload image files in asp.net and How to create thumbnail, small and large version of the uploaded image in Asp.net and How to resize image in Asp.net and How to check and validate file extension before uploading a file through FileUpload control in asp.net.
 In this article we are limiting the size of the images to maximum 2 mb(2097152 bytes). If the user try to upload image larger  than 2 mb(Mega Byte)  then it will show message  "Please upload jpg/jpeg/png/gif image of upto 2mb size only" and not allow to upload the image.

C#.NET Code to restrict user to upload images of up to specified size

protected bool ValidateImageSize()
    {
        int fileSize = FileUpload1.PostedFile.ContentLength;
        //Limit size to approx 2mb for image
        if ((fileSize > 0 & fileSize < 2097152))
        {
            return true;
        }
        else
        {
           Response.WriteFile("Please upload jpg/jpeg/png/gif image of upto 2mb size only");        
            return false;
        }
    }

Now call this function the functions ValidateImageSize() on the Upload/Submit button before actual image   upload coding.

VB.NET Code to restrict user to upload images of up to specified size
Protected Function ValidateImageSize() As Boolean
        Dim fileSize As Integer = FileUpload1.PostedFile.ContentLength
        'limit size to approx 2mb  for image
        If (fileSize > 0 And fileSize < 2097152) Then
            Return True
        Else
            Response.WriteFile("Please upload jpg/jpeg/png/gif image of upto 2mb size only")
            Return False
        End If
    End Function

Now call this function the functions ValidateImageSize() on the Upload/Submit button before actual image   upload coding.
Previous
Next Post »

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..