7

I'm trying to display the file size of a file uploaded in Assets. I can get it to display the number of bytes in the file. https://craftcms.com/docs/templating/craft.assets#size

Is there a way to format that number to Mb's?

3 Answers 3

12

This should do it:

{% set bytes = asset.size %}
{% set kiloBytes = (bytes / 1024)|round(2) %}
{% set megaBytes = (kiloBytes / 1024)|round(2) %}

bytes = {{ bytes }}
kiloBytes = {{ kiloBytes }}
megaBytes = {{ megaBytes }}

You can look at Twig's number_format filter if you want to get fancy with how to display the numbers.

7

You now can use the filesize filter: https://docs.craftcms.com/v3/dev/filters.html#filesize. This will make the file size readable, and the unit will be selected automatically.

2
  • 1
    As an extension to this answer, as it is specific to the question, as of Craft 3.1.21 the filesize filter now formats using metric units: github.com/craftcms/cms/blob/develop/…
    – Jamie Wade
    Apr 10, 2019 at 16:20
  • 3
    I've discovered that you can even round the |filesize filter by adding a round parameter: |filesize(1). Maybe there's even more?
    – outline4
    Oct 15, 2019 at 7:47
1

As mentioned before, the filesize filter is your friend: https://craftcms.com/docs/4.x/dev/filters.html#filesize

Internally, this uses a yii Formatter. You can supply additional arguments to the filter. Here is a link to the function Craft is calling internally: https://www.yiiframework.com/doc/api/2.0/yii-i18n-formatter#asShortSize()-detail

Be aware that Craft's default base for calculating file sizes is 1000, not 1024. This lead to some unwanted results while I was working with it. I ended up overriding the global setting like this:

Craft::$app->formatter->sizeFormatBase = 1024;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.