我得到这段代码通过PHP隐蔽大小字节。

现在我想使用JavaScript将这些大小转换为人类可读的大小。我尝试将这段代码转换为JavaScript,看起来像这样:

function formatSizeUnits(bytes){
  if      (bytes >= 1073741824) { bytes = (bytes / 1073741824).toFixed(2) + " GB"; }
  else if (bytes >= 1048576)    { bytes = (bytes / 1048576).toFixed(2) + " MB"; }
  else if (bytes >= 1024)       { bytes = (bytes / 1024).toFixed(2) + " KB"; }
  else if (bytes > 1)           { bytes = bytes + " bytes"; }
  else if (bytes == 1)          { bytes = bytes + " byte"; }
  else                          { bytes = "0 bytes"; }
  return bytes;
}

这是正确的做法吗?有没有更简单的方法?


当前回答

函数by睾丸(字节){ const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; If (bytes === 0)返回'n/a'; const i = Math.min(Math.floor(Math.log(bytes) / Math.log(1024))),大小。长度- 1); 如果(i === 0)返回' ${bytes} ${sizes[i]} '; 返回“${(字节/(1024 * *我)).toFixed(1)} ${大小[我]}'; } console.log (bytesToSize (400000)) console.log (bytesToSize (5000000))

其他回答

一行程序

const b2s = t = > {let’e = Math .对数(t) / 10 | 0; return (t / 1024 * * (e = e < = 0 ? 0 toFixed: e))(3) +“BKMGP”[e]}; console . log (b2s (0)); console . log (b2s (123)); console . log (b2s (123123)); console . log (b2s (123123123)); console . log (b2s (123123123123)); console . log (b2s (123123123123123));

试试这个简单的解决方法。

var files = $("#file").get(0).files;               
                var size = files[0].size;
                if (size >= 5000000) {
alert("File size is greater than or equal to 5 MB");
}

根据al冰岛m的答案,我在小数点后去掉了0:

function formatBytes(bytes, decimals) {
    if(bytes== 0)
    {
        return "0 Byte";
    }
    var k = 1024; //Or 1 kilo = 1000
    var sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
    var i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(decimals)) + " " + sizes[i];
}

您可以使用filesizejs库。

var大小=[“字节”,“知识库”,“m”,“g”,“结核”,“铅”、“海尔哥哥”,“ZB”,“YB”); 函数formatBytes(字节,小数){ For (var I = 0, r = bytes, b = 1024;R > b;I ++) r /= b; 返回' ${parseFloat(r.toFixed(decimal))} ${SIZES[i]} '; }