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?
Craft CMS Stack Exchange is a question and answer site for administrators, end users, developers and designers for Craft CMS. It only takes a minute to sign up.
Sign up to join this communityI'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?
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.
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.
Craft 3.1.21
the filesize
filter now formats using metric units: github.com/craftcms/cms/blob/develop/…
Apr 10, 2019 at 16:20
|filesize
filter by adding a round parameter: |filesize(1)
. Maybe there's even more?
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;