5

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?

9

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.

| improve this answer | |
5

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.

| improve this answer | |
  • 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 '19 at 16:20
  • 1
    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 '19 at 7:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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