Tuesday, February 14, 2012

Using javascript check uploaded file size

write function in JavaScript

Note:- Only working with FireFox,Crome,Safari,Opera 
for Internet Explorer check this page

function aditya(source, args)
    {
    arguments.isvalid = false;
    fileupload = document.getElementById('<%= FileUpload2.ClientID %>');
    file=fileupload.files[0];
    if (file.size<1048576)
    {
     args.IsValid =  true;
    }
    else
    {
     args.IsValid = false ;
    }
    return ;
    }

use this function in Custom Validator Field
<asp:FileUpload ID="FileUpload2" runat="server" />
<asp:CustomValidator ID="abc" runat="server" ErrorMessage="Max File Size is 1 MB" ControlToValidate="FileUpload2" ClientValidationFunction="aditya"></asp:CustomValidator>




==========================================================================
Example:---

==========================================================================





<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>

    <script language="javascript" type="text/javascript">
    function aditya(source, args)
    {
    arguments.isvalid = false;
    fileupload = document.getElementById('<%= FileUpload2.ClientID %>');
    file=fileupload.files[0];
    if (file.size<1048576)
    {
     args.IsValid =  true;
    }
    else
    {
     args.IsValid = false ;
    }
    return ;
    }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="FileUpload2" runat="server" />
        <asp:RegularExpressionValidator ID="ValidateResume" runat="server" ErrorMessage="Only pdf files allowed."
            ValidationExpression="^.+\.(([pP][dD][fF]))$" ControlToValidate="FileUpload2" />
        <asp:CustomValidator ID="abc" runat="server" ErrorMessage="Max File Size is 1 MB" ControlToValidate="FileUpload2"
            ClientValidationFunction="aditya"></asp:CustomValidator>
    </div>
    </form>
</body>
</html>



5 comments:

  1. Replies
    1. its not working in IE because fileupload.files[0]; is not supported by IE. this is working very fine in any other browser.

      Delete
    2. http://criticalcodes.blogspot.in/2012/03/using-javascript-check-uploaded-file.html

      check this link i updated code.

      Delete
  2. It's asp.net right?what to do in PHP

    ReplyDelete
    Replies
    1. Check this

      http://criticalcodes.blogspot.in/2012/04/using-javascript-check-uploaded-file.html

      Delete