Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Bytes to KB/MB in Javascript [duplicate]

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.

like image 222
Akash M Avatar asked Mar 21 '18 07:03

Akash M


1 Answers

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

like image 72
Pieter Tielemans Avatar answered Oct 01 '22 15:10

Pieter Tielemans