Search code examples
jqueryfile-uploadpostdata

How can I check the POST data size before I submit it with jQuery?


I have a web app that allows users to add multiple images, and then upload them, along with other data, all at once when they press a Save button. I'm trying to calculate total size of the POST data before it is sent, so that I can break up the request into multiple ones to avoid hitting PHP's post_max_size or max_file_uploads errors.

Currently, I'm using this code to check only the overall size of the images using the HTML5 File API (size property):

// Calculate size of all files being submitted
var ttlSize = 0;
$('form').find('input[type=file]').each(function() {
    ttlSize += this.files[0].size;
});

if (ttlSize > 4 * 1048576) { // >4MB
    // this will exceed post_max_size PHP setting, now handle...
} else if ($('form').find('input[type=file]').length >= 10) {
    // this will exceed max_file_uploads PHP setting, now handle...
}

I'd like to be more precise by including the rest of the POST data. Is this possible?


Solution

  • You can estimate it by counting the length of your serialized form, excluding file upload fields. So it would be somewhere along these lines:

    $("form").not("[type='file']").serialize().length;