Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can i format a file size using php?

I have a form where i am uploading a file after successfully file uploaded i want to show a size of each file with KB, MB, GB depends on the file size.

Like this

<div class="d-flex align-items-center gap-3">
  <img src="{{asset('images/icons/file-icon.svg')}}" alt="" style="width: 70px;height: 70px;border-radius: 10px;">
  <div>
    <p class="font-weight-bold m-0 text-primary-dark">{{ $media->name }}</p>
    <p class="m-0 font-weight-bold text-primary-dark">{{ formatFileSize($media->size) }}</p>
  </div>
</div>

I have create a function in which i am sending a size like this in my blade

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{{ formatFileSize($media->size) }}

this should give me a proper format with the unit

>Solution :

You can acheive this by using a helper function like this

function formatFileSize($size): string
{
  $units = ['B', 'KB', 'MB', 'GB', 'TB'];
  $base = 1024;
  $unitIndex = 0;

  while ($size >= $base && $unitIndex < count($units) - 1) {
    $size /= $base;
    $unitIndex++;
  }

  return round($size, 2) . ' ' . $units[$unitIndex];
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading