The following snippet uses custom validator control and javascript to check the file upload size and disabling the form submission if the file size exceeds the limit. The form will not submit if the validator fails.
ASPX.PAGE
[sc:tcbox ]<asp:FileUpload ID=”fileUpload” runat=”server” />
<br />
<asp:CustomValidator ID=”customValidatorUpload” runat=”server” ErrorMessage=”Files is too large” ControlToValidate=”fileUpload” ClientValidationFunction=”ValidateFileSize” />
<br />
<asp:Button ID=”button_fileUpload” runat=”server” Text=”Upload File” OnClick=”button_fileUpload_Click” />
Javascript custom validate function
[sc:tcbox ]<script type=”text/javascript”>
function ValidateFileSize(sender, args) {
var maxFileSize = 1 // 1MB -> 1 * 1024 – to check in KB – Kilo Bytes
var fileUpload = document.getElementById(“<%=fileUpload.ClientID%>”);
if (typeof (fileUpload.files) != “undefined”) {
var size = parseFloat(fileUpload.files[0].size / 1024).toFixed(2);
if (size < maxFileSize) {
args.IsValid = true;
} else {
args.IsValid = false;
}
} else {
alert(“You have an outdated browser”);
}
}
</script>
[sc:/tcbox ]This snippet will not work in old browsers.