I'd like to get the real filename of a file entity.

My code is like this

    $filenames = [];
    foreach ($entity->$field->referencedEntities() as $image) {
      // Filename.
      $media = Media::load($image->id());
      $fid = $media->field_media_image->target_id;
      $file = File::load($fid);
      $filenames[] = $file->getFilename();

    return $filenames;

But filename returns the label of the file entity like so. my-image.jpg and using getFileUri() returns public://images/my-image_0.jpg I think because the image has been replaced at some point.

What I would like is just my-image_0.jpg but I can't seem to find a function to do it.


1 Answer 1


The File class itself, in File::preCreate() uses the following code.

  // Automatically detect filename if not set.
  if (!isset($values['filename']) && isset($values['uri'])) {
    $values['filename'] = \Drupal::service('file_system')

In you case, the following code should be used.

$filenames[] = \Drupal::service('file_system')->basename($file->getFileUri());

In a context where dependency injection is available, the file_system service should be injected.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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