Click here to Skip to main content
14,739,359 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to validate size of a uploaded file using file upload control in asp.net(C#), which is not more than 200kb.
I tried

<script language="javascript" type="text/javascript">
    function getFileSize()
    {
    debugger;
   // alert("hello");
    var strFileName= document.getElementById("FUAttachContract").value;
    //alert(strFileName);
    var objFSO = new ActiveXObject("Scripting.FileSystemObject");
   // alert(objFSO);
    var e = objFSO.getFile(strFileName);
    var fileSize = e.size;
    alert(fileSize);
        if (fileSize > 204800) {
            alert('size more than 200KB');
        }
    }
    </script>

<form id="form1" runat="server">
       <asp:FileUpload ID="FUAttachContract" runat="server" />
       <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="javascript:getFileSize();" />
   </form>


Its working fine when I manually enable the ActiveX object, I want suggestion without using ActiveX Object.
Posted

Yes, there's a new feature from the W3C that's supported by some modern browsers, the File API. It can be used for this purpose, and it's easy to test whether it's supported and fall back (if necessary) to another mechanism if it isn't.

http://stackoverflow.com/a/3717847/540653[^]
   
Comments
AshishChaudha 13-Jul-12 8:16am
   
Nope, I tried in IE8, It's showing "The file API isn't supported on this browser yet"
In Mozilla, It' showing "Um, couldn't find the fileinput element."
StianSandberg 13-Jul-12 9:00am
   
As i said: "supported by some modern browsers" This is not widely supported and should not be used in public websites without a fallback solution.
Sandeep Mewara 13-Jul-12 10:34am
   
This is HTML5 based feature and IE has it from IE9.
My suggestion, if you want to avoid ActiveX route, and you want to make sure that file above a certain length is not uploaded then you can set the size limit in config file:
<system.web>
    <httpRuntime  maxRequestLength="2048"/>
</system.web>

Down side of it: any file greater than defined size would lead page to display "This page cannot be displayed" so you need to catch this error and handle it.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900