Search code examples
javascriptjqueryhtml

Get total size of combined uploaded files with JQuery/Javascript


I have a page where a user can upload a document. There is also a button to add more documents (as seen per image).

Dynamicaly added upload points

after adding upload button

I want to check as each file that has been added or removed from the upload section to make sure that the size does not exceed 10 MB.

So if a user uploads 3 separate files of 2 MB and then adds a file which is 5 MB, the submit button will disable until one of the files are removed because it has gone over the 10 MB limit.

The rows can be added dynamically, so I was doing it by class and trying to sum the running total.

Here is what I have so far, available at JFIDDLE

<form class="upload-form">
  <input class='upload-file' type="file" id="upload0">
  <input class='upload-file' type="file" id="upload1">
  <input class='upload-file' type="file" id="upload2">
  <input class='upload-file' type="file" id="upload3">
  <input id='submitBtn' type=submit>
</form> 

The issue is, that if I add a file and then remove it, it does not reflect the current running total.

$("document").ready(function() {

  var fileArr = [];

  $(".upload-file").on('change',function() {
    var fileInput = $('.upload-file');

    var fileSize = fileInput.get(0).files[0].size;
    fileArr.push(fileSize);

    var totalSize = 0;

    for (var i in fileArr) {
      alert(fileArr[i]);
      totalSize = totalSize + fileArr[i];             
    }

    if (totalSize > 10485759) {
      alert('Over Max Size');
      $(submitBtn).prop("disabled",true);
    }

  });
});

I tried this way also, but could not reset when a file was removed.JFIDDLE-2


Solution

  • The logic in your code can be simplified by just incrementing a single counter within the each() loop. You can then check the total once the loop has completed to see if the combined file size is valid. Try this:

    $(".upload-file").on('change', function() {
      var totalSize = 0;
    
      $(".upload-file").each(function() {
        for (var i = 0; i < this.files.length; i++) {
          totalSize += this.files[i].size;
        }
      });
    
      var valid = totalSize <= 10485759;
      if (!valid) 
        alert('Over Max Size');
    
      $("#submitBtn").prop("disabled", !valid);
    });
    

    Note that this method will also work with multiple file inputs, as the jsFiddle below shows:

    Updated fiddle