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