Wednesday, November 27, 2013

Javascript to Validate File Size of FileUpload Control in asp.net

4 comments
Using Javascript code file size of asp.net file upload control can be checked and if the uploaded file size is more than the required size then custom message can be displayed to the user. To validate file size use the custom validator and set the ClientValidationFunction to javascript function which will check the file size and set the ControlToValidate property  of asp.net custom validator control to id of File Upload Control.

Note the file size which is compared in this example must be in kb. In this example If uploaded image  size is greater than 100kb(102400 bytes) then custom message would be displayed. You can change this value according to your requirement.

Sample Javascript Code to validate File Size of FileUpload Control:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default3.aspx.cs" Inherits="Default3" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
function checkfilesize(source, arguments)
{
 arguments.IsValid = false;
 var size = document.getElementById("<%=fupuploadimg.ClientID%>").files[0].size;
 if (size > 102400) {
 arguments.IsValid = false;
 return false;

 }
  else {

arguments.IsValid = true;
return true;

 }
 }

</script>
    <title></title>
</head>
<body>
  <form id="form1" runat="server">
  <div style="float:left;margin-left:100px; margin-top:50px;">
 <b>Upload File:</b> &nbsp; <asp:FileUpload ID="fupuploadimg" runat="server"  />
      &nbsp;&nbsp;&nbsp;&nbsp;  <asp:CustomValidator id="cvvalidate" runat="server" 
  ToolTip="FileSize should not exceed 1MB" Style="color: #FF0000;
  display: inline; float: left; font-family: arial; font-size: 13px; margin-left: 100px;
  margin-top:10px;" ValidationGroup="a"
  ErrorMessage="FileSize Exceeds the Limits."
  ControlToValidate="fupuploadimg" 
 ClientValidationFunction = "checkfilesize"></asp:CustomValidator>
 </div>
</form>
</body>
</html>


4 comments:

  1. This option is quite appealing. Is there a way to apply this approach if the user's browser does not support the .file[0] attribute? I can only get the .value attribute from my FileUpload object. I am also unable to create an ActiveXObject of type Scripting.FileSystemObject. Thanks for the consideration.

    ReplyDelete