Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh

How to display the size of a file in Drupal 8 & 9


Example How to display the size of a files in Drupal 8 & 9:

function THEMENAME_preprocess_image_widget(&$variables)
  if (!empty($variables['element']['fids']['#value'])) {
    $file = reset($variables['element']['#files']);
    $variables['data']["file_{$file->id()}"]['filename']['#suffix'] = ' <span class="file-size">(' . format_size($file->getSize()) . ')</span> ';


And to display the size and format of a file attached to an article or any other content type you can use this method:

function THEMENAME_preprocess_node(&$vars) {
  $node = $vars['node'];
  $type = $node->getType();
  if( $type == "article" && $node->hasField('field_file')){
      $file = $node->get('field_file')->entity;
      $vars["file_size"] = $file->getSize();
      $vars["file_type"] = $file->getMimeType();     


Add new comment

Restricted HTML


Page Facebook

Become a patron

If you need some help or you search a Drupal freelancer don't hesitate to contact us.


Contact Us

All the content is FREE but I still need your help


Become a patreon