Skip to main content
Category:

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();     
  }
}

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook