3

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?

Matt Baer
  • 1,267
  • 1
  • 12
  • 11

2 Answers2

1

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;

N.B.
  • 13,688
  • 3
  • 45
  • 55
  • Awesome, this seems to be exactly what I need. Currently my numbers client- and server-side are off due to some bad math, but will figure out what's going on and give final results. – Matt Baer Nov 16 '12 at 18:54
  • It looks like this method gives a result short of the actual `Content-length` by a number of bytes that grows with how many fields you're submitting, as well as which browser you're using. But this is what I was looking for, thanks. – Matt Baer Nov 30 '12 at 02:29
  • I think this is not exact. By adding file sizes and form serialization, I think you're not taking care of the files metadata sent to server (as filename) nor the multipart/form-data format. It's a nice approach BTW. I would like to know an exact bulletproof solution. – David Strencsev Mar 15 '13 at 13:23
0

for security purposes the access to file upload elements is restricted to the file name. the only way to get access to files on the client machine is with html5 via the new FormData object. have a look here: FormData - Document Object Model. without this objects you can not get the size of the files. otherwise: why not implementing an asynchronous upload?

iRaS
  • 1,958
  • 1
  • 16
  • 29
  • I currently use the FileReader API to load the files into the DOM, and then construct and submit the form in an `iframe`. So I _can_ get the file sizes and it is asynchronous. (: – Matt Baer Nov 16 '12 at 18:55