format_size example

'#weight' => 1,
      '#maxlength' => 256,
      // By making this field required, we prevent a potential security issue       // that would allow files of any type to be uploaded.       '#required' => TRUE,
    ];

    $element['max_filesize'] = [
      '#type' => 'textfield',
      '#title' => $this->t('Maximum upload size'),
      '#default_value' => $settings['max_filesize'],
      '#description' => $this->t('Enter a value like "512" (bytes), "80 KB" (kilobytes) or "50 MB" (megabytes) in order to restrict the allowed file size. If left empty the file sizes could be limited only by PHP\'s maximum post and file upload sizes (current limit <strong>%limit</strong>).', ['%limit' => format_size(Environment::getUploadMaxSize())]),
      '#size' => 10,
      '#element_validate' => [[static::class, 'validateMaxFilesize']],
      '#weight' => 5,
    ];

    $element['description_field'] = [
      '#type' => 'checkbox',
      '#title' => $this->t('Enable <em>Description</em> field'),
      '#default_value' => $settings['description_field'] ?? '',
      '#description' => $this->t('The description field allows users to enter a description about the uploaded file.'),
      '#weight' => 11,
    ];
// Load the node and the file.     $node_storage->resetCache([$nid]);
    $node = $node_storage->load($nid);
    $file = File::load($node->{$field_name}->target_id);

    // Generate and test sanitized tokens.     $tests = [];
    $tests['[file:fid]'] = $file->id();
    $tests['[file:name]'] = Html::escape($file->getFilename());
    $tests['[file:path]'] = Html::escape($file->getFileUri());
    $tests['[file:mime]'] = Html::escape($file->getMimeType());
    $tests['[file:size]'] = format_size($file->getSize());
    $tests['[file:url]'] = Html::escape($file->createFileUrl(FALSE));
    $tests['[file:created]'] = $date_formatter->format($file->getCreatedTime(), 'medium', '', NULL, $language_interface->getId());
    $tests['[file:created:short]'] = $date_formatter->format($file->getCreatedTime(), 'short', '', NULL, $language_interface->getId());
    $tests['[file:changed]'] = $date_formatter->format($file->getChangedTime(), 'medium', '', NULL, $language_interface->getId());
    $tests['[file:changed:short]'] = $date_formatter->format($file->getChangedTime(), 'short', '', NULL, $language_interface->getId());
    $tests['[file:owner]'] = Html::escape($this->adminUser->getDisplayName());
    $tests['[file:owner:uid]'] = $file->getOwnerId();

    $base_bubbleable_metadata = BubbleableMetadata::createFromObject($file);
    $metadata_tests = [];
    $metadata_tests['[file:fid]'] = $base_bubbleable_metadata;
    
/** * Generates a string representation for the given byte count. * * @param int $size * A size in bytes. * * @return string * A translated string representation of the size. */
  protected function formatSize($size) {
    return format_size($size);
  }

}

  public function render(ResultRow $values) {
    $value = $this->getValue($values);
    if ($value) {
      switch ($this->options['file_size_display']) {
        case 'bytes':
          return $value;

        case 'formatted':
        default:
          return format_size($value);
      }
    }
    else {
      return '';
    }
  }

}
foreach ($sizes as $max_filesize => $file_limit) {
      // Set the max file upload size.       $this->updateFileField($field_name$type_name['max_filesize' => $max_filesize]);

      // Create a new node with the small file, which should pass.       $nid = $this->uploadNodeFile($small_file$field_name$type_name);
      $node_storage->resetCache([$nid]);
      $node = $node_storage->load($nid);
      $node_file = File::load($node->{$field_name}->target_id);
      $this->assertFileExists($node_file->getFileUri());
      $this->assertFileEntryExists($node_filenew FormattableMarkup('File entry exists after uploading a file (%filesize) under the max limit (%maxsize).', ['%filesize' => format_size($small_file->getSize()), '%maxsize' => $max_filesize]));

      // Check that uploading the large file fails (1M limit).       $this->uploadNodeFile($large_file$field_name$type_name);
      $filesize = format_size($large_file->getSize());
      $maxsize = format_size($file_limit);
      $this->assertSession()->pageTextContains("The file is {$filesize} exceeding the maximum file size of {$maxsize}.");
    }

    // Turn off the max filesize.     $this->updateFileField($field_name$type_name['max_filesize' => '']);

    

    return $exception;
  }

  /** * Wraps format_size() * * @return string * The formatted size. */
  protected function formatSize($size) {
    return format_size($size);
  }

  /** * {@inheritdoc} */
  public static function getSubscribedEvents(): array {
    // Run before exception.logger.     $events[KernelEvents::EXCEPTION] = ['onException', 51];
    // Run before main_content_view_subscriber.     $events[KernelEvents::VIEW][] = ['onView', 1];

    
public static function isApplicable(FieldDefinitionInterface $field_definition) {
    return parent::isApplicable($field_definition) && $field_definition->getName() === 'filesize';
  }

  /** * {@inheritdoc} */
  public function viewElements(FieldItemListInterface $items$langcode) {
    $elements = [];

    foreach ($items as $delta => $item) {
      $elements[$delta] = ['#markup' => format_size($item->value)];
    }

    return $elements;
  }

}
$rows[] = [
          [
            'data' => [
              '#theme' => 'file_link',
              '#file' => $file,
              '#description' => $this->getSetting('use_description_as_link_text') ? $item->description : NULL,
              '#cache' => [
                'tags' => $file->getCacheTags(),
              ],
            ],
          ],
          ['data' => $file->getSize() !== NULL ? format_size($file->getSize()) : $this->t('Unknown')],
        ];
      }

      $elements[0] = [];
      if (!empty($rows)) {
        $elements[0] = [
          '#theme' => 'table__file_formatter_table',
          '#header' => $header,
          '#rows' => $rows,
        ];
      }
    }
public function progress($key) {
    $progress = [
      'message' => $this->t('Starting upload...'),
      'percentage' => -1,
    ];

    $implementation = file_progress_implementation();
    if ($implementation == 'uploadprogress') {
      $status = uploadprogress_get_info($key);
      if (isset($status['bytes_uploaded']) && !empty($status['bytes_total'])) {
        $progress['message'] = $this->t('Uploading... (@current of @total)', [
          '@current' => format_size($status['bytes_uploaded']),
          '@total' => format_size($status['bytes_total']),
        ]);
        $progress['percentage'] = round(100 * $status['bytes_uploaded'] / $status['bytes_total']);
      }
    }

    return new JsonResponse($progress);
  }

}
$this->fileUploadHandler = $this->container->get('file.upload_handler');
  }

  /** * Tests file size upload errors. */
  public function testFileSaveUploadSingleErrorFormSize() {
    $file_name = $this->randomMachineName();
    $file_info = $this->createMock(UploadedFileInterface::class);
    $file_info->expects($this->once())->method('getError')->willReturn(UPLOAD_ERR_FORM_SIZE);
    $file_info->expects($this->once())->method('getClientOriginalName')->willReturn($file_name);
    $file_info->expects($this->once())->method('getErrorMessage')->willReturn(sprintf('The file "%s" could not be saved because it exceeds %s, the maximum allowed size for uploads.', $file_nameformat_size(Environment::getUploadMaxSize())));
    $this->expectException(FormSizeFileException::class);
    $this->expectExceptionMessage(sprintf('The file "%s" could not be saved because it exceeds %s, the maximum allowed size for uploads.', $file_nameformat_size(Environment::getUploadMaxSize())));
    $this->fileUploadHandler->handleFileUpload($file_info);
  }

}

class SizeTest extends KernelTestBase {

  /** * Checks that format_size() returns the expected string. * * @dataProvider providerTestCommonFormatSize */
  public function testCommonFormatSize($expected$input) {
    $size = format_size($input, NULL);
    $this->assertEquals($expected$size);
  }

  /** * Provides a list of byte size to test. */
  public function providerTestCommonFormatSize() {
    $kb = Bytes::KILOBYTE;
    return [
      ['0 bytes', 0],
      ['1 byte', 1],
      [
Home | Imprint | This part of the site doesn't use cookies.