Asp.Net Check file size before upload

ASPX

<asp:CustomValidator ID="customValidatorUpload" runat="server" ErrorMessage="" ControlToValidate="fileUpload" ClientValidationFunction="setUploadButtonState();" />
<asp:Button ID="button_fileUpload" runat="server" Text="Upload File" OnClick="button_fileUpload_Click" Enabled="false" />
<asp:Label ID="lbl_uploadMessage" runat="server" Text="" />

jQuery

function setUploadButtonState() {

   var maxFileSize = 4194304; // 4MB -> 4 * 1024 * 1024
   var fileUpload = $('#fileUpload');

   if (fileUpload.val() == '') {
    return false;
   }
   else {
      if (fileUpload[0].files[0].size < maxFileSize) {
         $('#button_fileUpload').prop('disabled', false);
         return true;
      }else{
         $('#lbl_uploadMessage').text('File too big !')
         return false;
      }
   }
}

Leave a Comment