[RESOLVED]Client-Side File Size Check

I am using .NET 4.0, 4.5, VB.NET, and the asp:FileUpload functionality to upload a file from the client’s PC to my web server. Prior to actually doing the upload I need to verify that the file size is less than some limit that I set (Ex: 10240 KB).

I know that I can limit the file size in the web.config using the maxRequestLength parameter. However, if I set this parameter to 10240 and the client uploads a file larger than that, the application blows up with a very unfriendly message. I could set the
maxRequestLength to something greater than 10240 KB and then check the file size after it has been uploaded to see if it is less than 10240 KB, however there is still the possibility the client will submit a file larger than the maxRequestLength.

I need to check the file size from the client side prior to the upload, give the client a friendly message if the size is greater than whatever I want the maximum to be, and then prevent the upload from occurring.

Does anyone know how to do this?

 

=

Here is my JSfor this, using simple javascript you can check file size.  JSFiddle- http://jsfiddle.net/c6pz1huz/1/

<input type="file" id="fl"/>
<input type="button" value="check file size" onclick="Checksize();" />



function Checksize()
{
var k = document.getElementById("fl").files[0].size;
alert( "file size in KB " + k/1024 );
}

using jquery:

var fileSize = $('#your_upload_control').get(0).files[0].size;

This gets you the size in bytes, here’s a helper for formatting to your users:

//Method to format a files bytes
    function formatBytes(num) {

        if (num <= 1023) {
            return num + " bytes";
        }
        else if (num >= 1024 && num <= 1048575) {
            return Math.round(num / 1024) + " kb";
        }
        else {
            return Math.round(num / 1048576) + " mb"
        }

    }//end of formatBytes()

arindamnayak,

Maybe it is my limited knowledge of ASP.NET and VB.NET, but your solution does not seem to incorporate the use of the asp:FileUpload functionality. I am not certain how to implement your solution and the asp:FileUpload into a single solution.  

remojr76,

I have the same problem with your solution. How do I combine your solution with the asp:FileUpload?

I was saying that, you can use ID field of asp:fileupload in JS too!. I.e. following will work, i mean it is.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function checkfile()
        {
            var k = document.getElementById("fl").files[0].size;
            alert("file size in KB " + k / 1024);
            return false;
        }
    </script>

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:FileUpload ID="fl" runat="server" />
        <asp:Button ID="btncheck" runat="server" OnClientClick="return checkfile();" Text="Check" />
   </div>
    </form>
</body>
</html>

The asp:FileUpload functionality automatically generates a field (textbox for lack of a better term) and a Browse button. When you click on the Browse button you get a window which allows the user to locate (browse to) the file to be uploaded. When they
highlight that file and click "Open", the window closes and the file they specified is displayed in the field (textbox). It is at this moment that I need the client (in the code behind) to get the file size for the file, test it, and generate a message if
it is greater than whatever maximum I specify.

The asp:FileUpload does not have an OnChange event that would allow me to execute client side code to check the file size.

The code you sent me creates a separate button which the user must click or I have to find some way of executing the code behind automatically. I don’t want to rely on the user to click on this button. The Upload button (see the btnUpLoad_Click code behind
that is below) runs on the server and therefore cannot do the file size check until after the file has already been uploaded. 

 I do not understand exactly when the upload (file transfer from the client to the server) is performed. Does it happen upon completion of the Browse functionality when the file name is placed in the field (textbox) or does it happen when the FileUpload.SaveAsFile
statement (in the code below) is executed on the server? The following code is the OnClick event tied to an asp:Button which follows the asp:FileUpload.

    Protected Sub btnUpload_Click(ByVal sender As Object, ByVal e As EventArgs)
        'This sub comes from //www.dotnetbull.com/2013/03/how-to-upload-file-in-aspnet-using.html
        Debug.Print(Now() & " " & "FileUpload/FileUploadId.aspx, btnUpload_Click")

        Dim strFileSavePath As String
        Dim fileName As String = FileUpload.PostedFile.FileName
        Debug.Print(Now() & " " & "fileName=" & fileName)

        Dim fileExtension As String = System.IO.Path.GetExtension(fileName)
        Debug.Print(Now() & " " & "fileExtension=" & fileExtension & "|")

        Dim fileMimeType As String = FileUpload.PostedFile.ContentType
        Debug.Print(Now() & " " & "fileMimeType=" & fileMimeType & "|")

        Dim intfileLengthInKB As Integer = Math.Ceiling(FileUpload.PostedFile.ContentLength / 1024)
        Dim intfileLengthInMB As Integer = Math.Ceiling(intfileLengthInKB / 1024)
        Debug.Print(Now() & " " & "fileLengthInKB=" & intfileLengthInKB)

        Dim maxintfileLengthInKB As Integer = 10240    'max filesize = 10MB = 10240KB 
        Dim maxintfileLengthinMB As Integer = maxintfileLengthInKB / 1024
        Debug.Print(Now() & " " & "maxintfileLengthInKB=" & maxintfileLengthInKB)

        'The matchExtension and matchMimeType values come from 
        ' //www.telerik.com/help/aspnet-ajax/upload-mime-types.html
        Dim matchExtension As String = ".xls .xlsx"

        Dim matchMimeType As String = "application/excel application/vnd.ms-excel application/x-excel application/x-msexcel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

        If FileUpload.HasFile Then
            Debug.Print(Now() & " " & "HERE 1")
            Debug.Print(Now() & " " & "matchExtension.Contains(fileExtension)=" & matchExtension.Contains(fileExtension))
            Debug.Print(Now() & " " & "matchExtension.Contains(fileMimeType)=" & matchExtension.Contains(fileMimeType))
            If matchExtension.Contains(fileExtension) And matchMimeType.Contains(fileMimeType) Then
                Debug.Print(Now() & " " & "HERE 2")
                If intfileLengthInKB <= maxintfileLengthInKB Then
                    Debug.Print(Now() & " " & "HERE 3")
                    Try

                        Debug.Print(Now() & " " & "HERE 4")
                        If Me.Session("ProdTestServer") = "Prod" Then
                            strFileSavePath = "\CHEROKEE"
                        Else
                            strFileSavePath = "\dakotaishardingUploadedFiles"        'FOR TESTING
                            'strFileSavePath = "c:appsOnlineAgentData"        'FOR TESTING
                        End If
                        Debug.Print(Now() & " " & "strFileSavePath=" & strFileSavePath)

                        Dim strFileNameAtHCAD = "OAS_P_" & Session("gstr_v_Agent") & "_" & _
                                          DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss") & "_" & _
                                          FileUpload.FileName
                        Dim strSaveAsFile = strFileSavePath & strFileNameAtHCAD
                        Debug.Print(Now() & " " & "FileUpload.SaveAs=" & strSaveAsFile)

                        FileUpload.SaveAs(strSaveAsFile)
                        lbl_FileUploadMsg11.Text = "File Name: "
                        lbl_FileUploadMsg12.Text = FileUpload.PostedFile.FileName
                        lbl_FileUploadMsg21.Text = "File Size: "
                        lbl_FileUploadMsg22.Text = intfileLengthInKB & " kb"
                        lbl_FileUploadMsg31.Text = "File Extension: "
                        lbl_FileUploadMsg32.Text = fileExtension
                        lbl_FileUploadMsg41.Text = "Mime Type: "
                        lbl_FileUploadMsg42.Text = FileUpload.PostedFile.ContentType
                        lbl_FileUploadMsg51.Text = "HCAD Filename Is: "
                        lbl_FileUploadMsg52.Text = strFileNameAtHCAD
                    Catch ex As Exception
                        lbl_FileUploadMsg11.Text = "ERROR:"
                        lbl_FileUploadMsg12.Text = ex.Message.ToString()
                        lbl_FileUploadMsg21.Text = ""
                        lbl_FileUploadMsg22.Text = ""
                        lbl_FileUploadMsg31.Text = ""
                        lbl_FileUploadMsg32.Text = ""
                        lbl_FileUploadMsg41.Text = ""
                        lbl_FileUploadMsg42.Text = ""
                        lbl_FileUploadMsg51.Text = ""
                        lbl_FileUploadMsg52.Text = ""
                    End Try
                    Response.Write("File Uploaded Successfully")
                Else
                    lbl_FileUploadMsg11.Text = "ERROR: "
                    lbl_FileUploadMsg12.Text = "Maximum upload file size is " & maxintfileLengthInKB & " KB (" & maxintfileLengthinMB & " MB). Your file size is " & intfileLengthInKB & " KB (" & intfileLengthInMB & " MB)."
                    lbl_FileUploadMsg21.Text = ""
                    lbl_FileUploadMsg22.Text = ""
                    lbl_FileUploadMsg31.Text = ""
                    lbl_FileUploadMsg32.Text = ""
                    lbl_FileUploadMsg41.Text = ""
                    lbl_FileUploadMsg42.Text = ""
                    lbl_FileUploadMsg51.Text = ""
                    lbl_FileUploadMsg52.Text = ""
                End If
            Else
                lbl_FileUploadMsg11.Text = "Informational: "
                lbl_FileUploadMsg12.Text = "Please select only .xls or .xlsx files."
                lbl_FileUploadMsg21.Text = ""
                lbl_FileUploadMsg22.Text = ""
                lbl_FileUploadMsg31.Text = ""
                lbl_FileUploadMsg32.Text = ""
                lbl_FileUploadMsg41.Text = ""
                lbl_FileUploadMsg42.Text = ""
                lbl_FileUploadMsg51.Text = ""
                lbl_FileUploadMsg52.Text = ""
            End If
        Else
            lbl_FileUploadMsg11.Text = "Informational: "
            lbl_FileUploadMsg12.Text = "You have not specified a file."
            lbl_FileUploadMsg21.Text = ""
            lbl_FileUploadMsg22.Text = ""
            lbl_FileUploadMsg31.Text = ""
            lbl_FileUploadMsg32.Text = ""
            lbl_FileUploadMsg41.Text = ""
            lbl_FileUploadMsg42.Text = ""
            lbl_FileUploadMsg51.Text = ""
            lbl_FileUploadMsg52.Text = ""
        End If

    End Sub

 

I just tested this and it works:

<div>

        <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />
    
    </div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script>

        $(function () {

            $('#myUpload').change(function () {

                alert($(this).get(0).files[0].size);

            });

        });
        

    </script>

Hope it helps!

I have tried the following without success:

                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;

When I use either one of the above lines of code I get the following message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

Using the $(‘#MainContent_FileUpload’).val() is am able to get the name of the file to be uploaded.

Below is the jscript code I am using, along with various lines of code that attempt to get the file size. None of them work. The code that gets fileName does work.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUpload').change(function () {
                alert("I AM HERE 2 !!");

                var objFileUpload = $('#MainContent_FileUpload')
//                var fileName = $('#MainContent_FileUpload').val();
                var fileName = objFileUpload.val();
                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUpload').size.val();
//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileSize = $('#MainContent_FileUpload').files[1].size();
//                var filesize = $('#MainContent_FileUpload').files.size;
//                var fileSize = this.files[0].size;
//                var filesize = this.files.size;
//                var fileSize = document.files[0].size;
//                var filesize = document.files.size;
//                var fileSize = objFileUpload.files[1].size();
//                var filesize = $(this).get(0).files[0].size;
                var filesize = $('#MainContent_FileUpload').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUpload').files[0].size;
//                var fileType = $('#MainContent_FileUpload').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

Does anyone have any other suggestions?

What is the name of your File Upload control? Best not to name if FileUpload since that’s already the name of the class. When referencing a control, you need to get it’s client id property. ASP.Net will generate a unique id for each control based on it’s
position in the control tree.

Try:

$('#<%= ControlName.ClientID %>')

This is a tricky control to work with client-side. The FIleUpload control actually isn’t rendering a field and a button, all it does is emit a file input control. <input type="file" > That’s all it does on that side really. It does a lot more though on the
server side to help you deal with the upload. The browsers and W3C keep the file input element sparse as far as what you can do with it to avoid it from becoming a security issue. Example: what would happen if you could set the filename, then you could swap
the user selected file for another more sensitive filename without them knowing. That’s one of the reasons it’s fairly tricky. Also, a lot of the features for doing things such as determining file size only work in newer browsers due to advances in HTML5.

markfitzme,

As you recommended I have renamed all references to my File Upload control to FileUploadToOAS.

I was not certain where to use the $("#… code you suggested so my first attempt was:

                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;
                alert('fileSize : ' + fileSize);

I am still getting the error message:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

on the "var filesize =…" statement.

Do you have any further suggestions?

Is the File upload control ClientIDMode set to Static?

  <asp:FileUpload ID="myUpload" ClientIDMode="Static" runat="server" />

 

remojr76,

Yes

<asp:FileUpload ID="FileUploadToOAS" Width="100%" ClientMode="Static" runat="server" />

you can use like this.

var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;
                alert('fileSize : ' + fileSize);

arindamnayak,

Your suggestion did not work.

Please see my jscript below.

Note the runtime errors that were generated for each of the attempts at getting the file size occurred on the line of code indicated except for the "//JavaScript runtime error: ‘fileSize’ is undefined" error which occurred on the "alert(‘fileSize
: ‘
+ fileSize);" statement.

    <script type="text/jscript" src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

    <script type="text/jscript">

        $(function () {
            //alert("I AM HERE 1 !!");
            $('#MainContent_FileUploadToOAS').change(function () {
//                alert("I AM HERE 2 !!");

                var objFileUploadToOAS = $('#MainContent_FileUploadToOAS')
//                var fileName = $('#MainContent_FileUploadToOAS').val();
                var fileName = objFileUploadToOAS.val();
//                alert('fileName : ' + fileName);

//                var fileSize = $('#MainContent_FileUploadToOAS').size.val();                  //JavaScript runtime error: Object doesn't support property or method 'val'
//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;               //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var fileSize = $('#MainContent_FileUploadToOAS').files[1].size();             //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').files.size;                  //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var filesize = MainContent_FileUploadToOAS.PostedFile.ContentLength;          //JavaScript runtime error: 'MainContent_FileUploadToOAS' is undefined
//                var filesize = objFileUploadToOAS.PostedFile.ContentLength;                   //JavaScript runtime error: Unable to get property 'ContentLength' of undefined or null reference
//                var fileSize = this.files[0].size;                                            //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = this.files.size;                                               //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = document.files[0].size;                                        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = document.files.size;                                           //JavaScript runtime error: Unable to get property 'size' of undefined or null reference
//                var fileSize = objFileUploadToOAS.files[1].size();                            //JavaScript runtime error: Unable to get property '1' of undefined or null reference
//                var filesize = $(this).get(0).files[0].size;                                  //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).files[0].size;        //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#<%= FileUploadToOAS.ClientID %>').get(0).files[0].size;    //JavaScript runtime error: Unable to get property '0' of undefined or null reference
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size;                 //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0);                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size;                        //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').size();                      //JavaScript runtime error: 'fileSize' is undefined
//                var filesize = $('#MainContent_FileUploadToOAS').get(0).size();               //JavaScript runtime error: Function expected
                var filesize = $('#<%= FileUploadToOAS.ClientID %>').files[0].size;             //JavaScript runtime error: Unable to get property '0' of undefined or null reference

                alert('fileSize : ' + fileSize);

//                var fileSize = $('#MainContent_FileUploadToOAS').files[0].size;
//                var fileType = $('#MainContent_FileUploadToOAS').files[0].type;
//                alert('FileName : ' + fileName + 'nFileSize : ' + fileSize + ' bytes');
//                //alert($(this).get(0).files[0].size);

            });

        });
    </script>

I have tried following , and it is working as expected. Note: your JS is wrong, as JS is case sensitive , if you have "var filesize " and later use "fileSize", it will not work, rather error will be shown.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
   
    <script type="text/javascript" >
        function onfilechange() {
            var fileSize = document.getElementById("<%= FileUploadToOAS.ClientID %>").files[0].size;
            alert('fileSize : ' + fileSize);
        }
        </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     
    </div>
        <asp:FileUpload ID="FileUploadToOAS" runat="server" onchange="onfilechange();"/>
        
    </form>
</body>

</html>

arindamnayak,

Is the onfilechange function executed on the server or on the client?

If it is executed on the server that means that the file must be uploaded before the filesize can be checked. I want the filesize checked before the upload occurs so that the user is prevented from uploading a file larger than the maximum I have specified
in my web.config file.

Additionally:

When I tried your suggestion using the onchange attribute with the asp:FileUpLoad I get the following message:

Message 3 Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’. C:Online Agent ServicesOASv2-2FileUploadFileUploadId.aspx 158 106 C:Online Agent ServicesOASv2-2

I tried running with the above error anyway and got the following message in the onfilechange function on the line where it is setting the var filesize =:

JavaScript runtime error: Unable to get property ’0′ of undefined or null reference

I am still looking for a solution to the problem of client-side file size check. None of the suggestions above have worked.

Thanks.

All i can say is, it is working for me, and onchange is  JS attribute, that might not get detected by VS. So finally you are getting JS error.

If you put the code i had given in an ASPX and browse, check view source, you will get the following

<input
type
="file"
name
="FileUploadToOAS" id="FileUploadToOAS"
onchange="checkfile();" />

i.e. it translates to simple input type file, so it should work.

Can you do rightclick-view source and paste that specific HTML here.

arindamnayak,

The asp:FileUpload functionality generates an input type="file" as you indicated. However, it also generates a browse button which, when clicked, opens a window allowing the user to browse to the file on their network to be uploaded. The "onchange=" event
gets a "Validation (ASP.Net): Attribute ‘onchange’ is not a valid attribute of element ‘FileUpload’" message in the Error List.

Below is the code generated as seen in the "View Source":

                                <tr>
                                    <td colspan="1" align="right"  style="width:15%; padding-right:5px;">
                                        <span id="MainContent_Label15" style="display:inline-block;color:Black;width:100%;">File :</span>
                                    </td>
                                    <td colspan="1" align="left" style="width:85%; text-align:left; padding-top:0px;" >
                                        <input type="file" name="ctl00$MainContent$FileUploadToOAS" id="MainContent_FileUploadToOAS" onchange="CheckFileSize()" style="width:100%;" />
                                        
                                        
                                    </td>
                                </tr>

Below is the CheckFileSize function:

    <script type="text/javascript" >
        function CheckFileSize() {
            var fileSize = document.getElementById("MainContent_FileUploadToOAS").files[0].size;
            alert('CheckFileSize, fileSize : ' + fileSize);
        }
    </script>

It’s not really generating a button. The browser does that for an input type=file, not HTML or ASP.Net. ASP.Net won’t allow onchange because it’s not a supported property. You can add it in codebehind though like so:

if(!Page.IsPostBack)
{FileUploadToOAS.Attributes.Add("onchange","CheckFileSize()");}

Hi,

Have you tried the http://jsfiddle.net/c6pz1huz/1/ Fiddle posted earlier? Does it work with your browser?

What is the browser you are using to test suggestions which are made?

With the code you have give, it should work. Yes, VS might show warning  that, onchange is not valid, But JS work this way only. If that is not working, there can be some JS error , you are getting in browser, can you post those error, or  "CheckFileSize",
is not invoked at all?

Leave a Reply