12

I want to convert file size MB format which is coming in Bytes at present.

Below is my code:

var x = document.getElementById("file");
var txt = "";
var totalSize = 0;

if ('files' in x) {
    if (x.files.length == 0) {
        txt = "Select one or more files.";
    } else {
        for (var i = 0; i < x.files.length; i++) {
            txt += "<br><strong>" + (i+1) + ". file</strong><br>";
            var file = x.files[i];
            if ('name' in file) {
                txt += "name: " + file.name + "<br>";
            }
            if ('size' in file) {
                totalSize += file.size;
                txt += "size: " + file.size + " bytes <br>";
            }
        }
    }
}
document.getElementById ("displayTotalSize").innerHTML = totalSize;
document.getElementById ("displaySize").innerHTML = txt;

The Output of the

document.getElementById ("displayTotalSize").innerHTML = totalSize;

is coming correctly which is in Bytes:

3145981

Now I want this to be converted to MB.

Please help me.

Akash M
  • 488
  • 3
  • 6
  • 18
  • `(totalSize/1048576).toFixed(1) + 'MB'` = taken from [MDN Web Docs](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file) – heakinakai Mar 21 '18 at 07:52

1 Answers1

38

you need to divide the totalSize through 1024^2 for MB, for KB you need 1024^1, and for GB you should divide throug 1024^4

var totalSizeKB = totalsize / Math.pow(1024,1)
var totalSizeMB = totalsize / Math.pow(1024,2)
var totalSizeGB = totalsize / Math.pow(1024,3)

which wil give you 3.000241279602051MB

Pieter Tielemans
  • 624
  • 5
  • 15