Daniel Lematy Daniel Lematy - 5 months ago 7
Javascript Question

JavaScript how can I add all the file sizes together?

When I select the files I want, I want to alert all the sizes together. So if I upload 3 files and on is 100bytes and one is 200 bytes and one is 500 bytes. I want it to alert 800 bytes. At the moment its alerting each one at a time.

This is the function

function upload(e){
e.preventDefault();
e.stopPropagation();

var file = document.getElementById("file");

for(var i = 0; i < file.files.length; i++){
var each = file.files[i];
var sizes = each.size;

alert(size);
}

startupload();
}

Answer

You were using alert inside the loop :

function upload(e){
    e.preventDefault();
    e.stopPropagation();

    var file = document.getElementById("file"),
        size = 0;

    for(var i = 0; i < file.files.length; i++){
        var each = file.files[i];
        var sizes = each.size;
        size += sizes;
    }
     alert(size);

    startupload();
}