How to add the size of all files with JS

0

I have a input file that receives several files, but I only managed to get the size of the first one. I would like to know how to take the size of all and add in a variable;

var sizeTotal = $("#inputfileSendTorrent")[0].files[0].size;

<input type="file" multiple name="inputfileSendTorrent[]" id="inputfileSendTorrent"> 
    
asked by anonymous 02.03.2017 / 20:29

2 answers

3

var getSize = function() {
  var size = 0;
  for (var i = 0; i < $("#inputfileSendTorrent")[0].files.length; i++) {
    size += $("#inputfileSendTorrent")[0].files[i].size;
  }

  console.log(size); // apenas para você ver o valor
  return size;
}

// basta chamar a função quando for usar: getSize()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="file" multiple name="inputfileSendTorrent[]" id="inputfileSendTorrent" onchange="getSize()">
    
02.03.2017 / 20:53
0

In your line

var sizeTotal = $("#inputfileSendTorrent")[0].files[0].size;

Files are an array of files and files [0] are the first in the list.

You need to pass all elements of this array:

var sum = 0;
var files = $("#inputfileSendTorrent")[0].files;

for(var i = 0; i < files.length; i++){
  sum += files[i].size;
}
//o resultado está em 'sum': console.log(sum);
    
02.03.2017 / 20:53