Michael
Michael

Reputation: 13614

Some misunderstanding using jQuery files[].size function with and ASP.NET FileUpload control.

I am new to Jquery and ASP.NET so maybe my question will seem naive to some of you.

I need to check file size before upload it to the server.

I have this ASP.NET code:

        <div class="label">
            Select file           
        </div>
        <asp:FileUpload ID="fileAsyncUpload" runat="server" Width="270" />
        <asp:Button ID="Button1" runat="server" Text="Upload" OnClientClick="GetFileSize()" />
    </div>

I have this jquery functions:

function GetFileSize() {
    try {
        var fileSize = 0;
        fileSize = $("#" + '<%= fileAsyncUpload.ClientID %>')[0].files[0].size;
        fileSize = fileSize / 1048576;
        confirm("Upload file size is :" + fileSize + "Mb")

    } catch (e) {
        alert("Error is:" + e);
    }
}

I googled and found the function GetFileSize() above.

But I cant understand this row:

$("#" + '<%= fileAsyncUpload.ClientID %>')[0].files[0].size;

How does it knows file size? Does it load to browser and then check the size of the file? Or it check the size on client computer?

Upvotes: 0

Views: 41

Answers (1)

choz
choz

Reputation: 17858

Your GetFileSize function runs in your browser (not on your IIS server). That's a javascript function, which also considered as a client script.

When the users finish selecting the file that they want to upload with <input type=file> element, the browser has performed such as handshake operation which lets the selected file's attributes are readable by the browser. So, it wouldn't be weird if the browser can read the size, would it?

Basically, your ASP.Net markup will render something like this but not exact in HTML,

<div class="label">
    Select file           
    </div>
        <input type='file' id='ctl00$YourParentControlsOrNot$fileSyncUpload' />
        <input type='submit' id='ctl00$YourParentControlsOrNot$Button1' onclick='GetFileSize()' onsubmit='ctl00$blablabla'>Upload</input>
    </div>
</div>

Note: Ignore the element IDs, they're assigned like that if you set your ClientIDMode to AutoID, otherwise It'd look like YourParentControl_Button1 if you set it to Predictable or even just Button1 if you set it to Static.

// This returns your FileUpload control client id, which can be used with javascript.
<%= fileAsyncUpload.ClientID %> 

// This will make it as a javascript element. (Not jQuery),
$("#" + '<%= fileAsyncUpload.ClientID %>')[0] 

// This will return the size of that file.
$("#" + '<%= fileAsyncUpload.ClientID %>')[0].files[0].size 

The same case with This sample.

Upvotes: 1

Related Questions