How to add the size of all JS files

Asked

Viewed 135 times

0

I have a input file that receives several files, however 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"> 
  • You have a file type input that can receive multiple files and want to know the size of each file?

  • @Laerte No, of all summed up.

  • Yes, but the input is file type right? Is that you wrote input size.

  • @Laerte Opa, I made a mistake, I already asked the question.

  • And that amount must be saved at the time the guy selects or at the time he sends?

  • In that same place there, in the case beforeSend:.

Show 1 more comment

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>
<input type="file" multiple name="inputfileSendTorrent[]" id="inputfileSendTorrent" onchange="getSize()">

0

In your line

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

Files is an array of files and files[0] is 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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.