-3

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

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

this should give me a proper format with the unit

  • Ok. So what exactly is the question / problem? If you have created the function, then what is the issue? We don't know what you want help with. Please [edit] your question to clarify it. See also [ask]. Thankyou – ADyson Aug 31 '23 at 09:41
  • Anything not working with that function? If yes, please share the code you are currently using. Also, please share how this problem is related to HTML or Laravel itself – Nico Haase Aug 31 '23 at 09:44
  • `this should give me a proper format with the unit`...ok. So, does it not do that? What is the problem? You still didn't actually explain any specific issue! – ADyson Aug 31 '23 at 09:52
  • Your question will get downvoted and closed unless you explain a specific problem and show your efforts so far. You have been lucky below (although it looks like a better solution already exists elsewhere - did you not search???), but in most cases, unless it's trivial, you will find that this is not a free write-my-code or do-my-googling service. See also the [tour], as well as the previously mentioned [ask], and [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). – ADyson Aug 31 '23 at 09:56
  • Duplicate of [Format bytes to kilobytes, megabytes, gigabytes](https://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes) (unless you can explain clearly why it's not the same issue) – ADyson Aug 31 '23 at 09:59

1 Answers1

-1

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];
}
  • 1
    There's no need for a loop. See for instance: https://stackoverflow.com/questions/2510434/format-bytes-to-kilobytes-megabytes-gigabytes – KIKO Software Aug 31 '23 at 09:46