In the previous tutorial I showed how to handle image uploads, how to validate some things and finally how to resize images retaining their proportions. This time I'll show you how to prevent uploading of files which size exceeds the defined limit. Well, this is not difficult to implement, however there are some pitfalls I'll tell you about later. Let's create a validator that will check if the size of an uploaded file is greater than the limit you set. We use a CustomValidator for this.
<asp:CustomValidator
ID="valFileSize"
runat="server"
ErrorMessage="The image exceeds 10 MB"
onservervalidate="valFileSize_ServerValidate"
Display="Dynamic"
/>
The method that actually performs the validation looks like this one:
protected void valFileSize*ServerValidate(object source, ServerValidateEventArgs args)
{
if (IsValid)
{
int maxSize = 5 * 1024 \_ 1024;
if (fileImage.PostedFile.ContentLength > maxSize)
{
args.IsValid = false;
}
}
}
Why do we check if the page is valid in the validation method? We check it, because the file size validation has sense only if there is an uploaded file and this file is an image. We should ensure that the validator that checks the file size is executed after all other validators, in order to make sure we should just put the corresponding CustomValidator after the other ones. On the other hand, we can have other fields on the form that we also want to validate and those fields are not connected to file uploading, in this case we can use a boolean field that will indicate whether file uploading is correct or not.
Well, if you run the web site and upload an image that is larger than 4 MB, you are likely to get a server error. This error is caused by uploading a file which size is larger than the maximum allowed size that is usually set to 4 MB. In order to extend that amount, you must correct Web.config, basically you need to set the maxRequestLength attribute of the httpRuntime element.
<httpRuntime maxRequestLength="20480"/>
In this example the maximum uploaded file size is set to 20 MB, because you set the value in KB, so 20480 = 20 \* 1024
.
You may also want to to set the value of the executionTimeout which will allow longer uploads.
However, you still cannot prevent a server from displaying an error if an uploaded file is larger than the value in Web.config, so it's recommended to set a deliberately large value and validate the file size programatically.
The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way. My personal thoughts tend to change, hence the articles in this blog might not provide an accurate reflection of my present standpoint.
© Mike Borozdin