Skip to content

Instantly share code, notes, and snippets.

@prashantdsala
Last active March 21, 2023 07:26
Show Gist options
  • Save prashantdsala/5bff168cb1cb94d49f6cfdd7bd0e6c12 to your computer and use it in GitHub Desktop.
Save prashantdsala/5bff168cb1cb94d49f6cfdd7bd0e6c12 to your computer and use it in GitHub Desktop.
How to load media entity and get the uploaded file details from media entity programatically in Drupal
<?php
use Drupal\media\Entity\Media;
use Drupal\file\Entity\File;
use Drupal\Core\Url;
// Load the media
$media_id = <Replace with the id of media entity>;
$media = Media::load($media_id);
// Get file id from the media.
$fid = $media->getSource()->getSourceFieldValue($media);
if (!empty($fid)) {
// Load file from fid
$file = File::load($fid);
// Get file name
$fileName = $file->getFilename();
// Get file URI
$uri = $file->getFileUri();
// Get file URL from URI
$fileUrl = Url::fromUri(file_create_url($uri))->toString();
// Get the file Mimetype.
$fileMimeType = $file->getMimeType();
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment