获取一个文件的大小并按以下要求转换单位:

  1. 如果文件大小小于1M,则以kb显示文件大小
  2. 如果文件大小在1M到1GB之间,则以MB显示文件大小
  3. 如果文件大小大于或等于1GB,则以GB显示文件大小

php具体实现源码如下:

<?php
function formatSizeUnits($bytes)
{
        if ($bytes >= 1073741824)
        {
            $bytes = number_format($bytes / 1073741824, 2) . \' GB\';
        }
        elseif ($bytes >= 1048576)
        {
            $bytes = number_format($bytes / 1048576, 2) . \' MB\';
        }
        elseif ($bytes >= 1024)
        {
            $bytes = number_format($bytes / 1024, 2) . \' kB\';
        }
        elseif ($bytes > 1)
        {
            $bytes = $bytes . \' bytes\';
        }
        elseif ($bytes == 1)
        {
            $bytes = $bytes . \' byte\';
        }
        else
        {
            $bytes = \'0 bytes\';
        }
        /*  http://www.manongjc.com/article/1414.html */
        return $bytes;
}
formatSizeUnits(filesize(\"/manongjc.pdf\"));
?>
收藏 打印