How to validate the size of uploaded file in BizForm

   —   
This article describes how you can validate the size of uploaded file in BizForm.
By default, BizForm functionality does not give you ability to verify the size of uploaded file. However, BizForm control provides the OnUploadFile event handler which is raised as soon as a file is uploaded. You can easily access the uploaded file in the code of the handler and compare its size with maximal allowed value.

First thing you need to do, is to register OnUploadFile handler in the SetupControl() of the BizForm web part (~\CMSWebParts\BizForms\bizform.ascx.cs):

else
{
// Set BizForm properties
viewBiz.FormName = this.BizFormName;
viewBiz.SiteName = this.SiteName;
viewBiz.UseColonBehindLabel = this.UseColonBehindLabel;
viewBiz.AlternativeFormFullName = this.AlternativeFormName;
viewBiz.ValidationErrorMessage = this.ValidationErrorMessage;
viewBiz.OnUploadFile += new EventHandler(viewBiz_OnUploadFile);
// Set the live site context
if (viewBiz.BasicForm != null)
{
viewBiz.BasicForm.ControlContext.ContextName = CMS.SiteProvider.ControlContext.LIVE_SITE;
}
}

The implementation of this handler could look like following one which ensures the maximal size of uploaded files to be 500 bytes:

void viewBiz_OnUploadFile(object sender, EventArgs e)
{

CMS.ExtendedControls.Uploader ctrlUploader = (CMS.ExtendedControls.Uploader)sender;
if ((ctrlUploader != null) && (ctrlUploader.PostedFile != null) && (ctrlUploader.PostedFile.ContentLength > 500))
{
// Display error message
Label errorLabel = ((Label)(viewBiz.FindControl("lblErrorLabel")));
if (errorLabel != null)
{
errorLabel.Text = "Uploaded file is too big!";
errorLabel.Visible = true;
}
// Stop bizform processing
viewBiz.StopProcessing = true;
}
}

As a result, a user will not be allowed to upload a file larger than 500 bytes:


-ml-


See also:

Applies to: Kentico CMS 5.5R2
Share this article on   LinkedIn