Last active
February 2, 2024 10:41
Drupal 9 - Working with files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\file\Entity\File; | |
// Load a file using its ID | |
$file = File::load($fid); | |
// Find a file using its URI | |
/** @var \Drupal\file\FileInterface[] $files */ | |
$files = \Drupal::entityTypeManager() | |
->getStorage('file') | |
->loadByProperties(['uri' => $found_file_url]); | |
/** @var \Drupal\file\FileInterface|null $found_file_url */ | |
$image = reset($files) ?: NULL; | |
// Get file details | |
$uri = $file->getFileUri(); // public://{location}/{file name}.{extension} | |
echo 'File name: ' . $file->getFilename . ', type:' . $file->getMimeType . ', size: ' . $file->getSize . ', Permanent:' . $file->isPermanent . ', Temporary:' . $file->isTemporary; | |
// Create a managed file. | |
/** @var \Drupal\Core\File\FileSystemInterface $filesystem */ | |
$filesystem = \Drupal::service('file_system'); | |
// Create file entity. | |
$image = File::create(); | |
$image->setFileUri($file_url); | |
$image->setOwnerId(\Drupal::currentUser()->id()); | |
$image->setMimeType('image/' . pathinfo($file_url, PATHINFO_EXTENSION)); | |
$image->setFileName($filesystem->basename($file_url)); | |
$image->setPermanent(); | |
$image->alt = 'Product image'; | |
$image->title = 'Product image'; | |
$image->save(); | |
// Assign the file to a file/image field | |
$variation->field_product_image = $image; | |
$variation->save(); | |
// Getting data from a file/image field | |
$image_field = $variation->field_product_image; | |
$tid = $existing_file_ref->target_id; | |
$alt = $existing_file_ref->alt; | |
$title = $existing_file_ref->title; | |
$width = $existing_file_ref->width; | |
$height = $existing_file_ref->height; | |
if (isset($tid)) { | |
// Load a file using its ID. | |
$file = File::load($tid); | |
$file_url = $file->getFileUri(); | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Build a URI | |
$directory = file_build_uri("folder"); // public://folder | |
$file = file_build_uri("folder/file.ext"); // public://folder/file.ext | |
// Use the file_system service to find jpg files in $directory | |
/** @var \Drupal\Core\File\FileSystemInterface $file_system */ | |
$file_system = \Drupal::service('file_system'); | |
$files = $file_system->scanDirectory($directory, '/.*\.jpg$/'); | |
// get info about the files found | |
foreach($files as $file) { | |
$file_name_no_ext = $file->name; | |
$file_name_with_ext = $file->filename; | |
$file_uri = $file->uri; | |
} | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Create media entity holding a reference to a managed file (like the one created in file_func.php). | |
/** @var \Drupal\media\MediaInterface $media */ | |
$image_media = Media::create([ | |
'bundle' => 'image', | |
'uid' => \Drupal::currentUser()->id(), | |
'langcode' => \Drupal::languageManager()->getDefaultLanguage()->getId(), | |
'status' => Media::PUBLISHED, | |
'field_image' => [ | |
'target_id' => $image->id(), | |
'alt' => t('Image for product '), | |
'title' => t('Image for product'), | |
], | |
]); | |
$image_media->save(); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\Core\File\FileSystemInterface; | |
class LoadAndSaveDataExample { | |
const FILE_SCHEME = 'private://'; | |
const DATA_CACHE_FOLDER = 'bank_of_england'; | |
const DATA_CACHE_FILENAME = 'mydata.xml'; | |
private function loadData() { | |
$directory = self::FILE_SCHEME . '/' . self::DATA_CACHE_FOLDER; | |
$file_path = $directory . '/' . self::DATA_CACHE_FILENAME; | |
return file_get_contents($file_path); | |
} | |
private function writeData($data) { | |
// Make sure folder exists | |
$directory = self::FILE_SCHEME . '/' . self::DATA_CACHE_FOLDER; | |
/** @var \Drupal\Core\File\FileSystemInterface $file_system */ | |
$file_system = \Drupal::service('file_system'); | |
$file_system->prepareDirectory($directory, FileSystemInterface::CREATE_DIRECTORY | FileSystemInterface::MODIFY_PERMISSIONS); | |
// Write the data | |
$file_path = $directory . '/' . self::DATA_CACHE_FILENAME; | |
/** @var \Drupal\file\FileRepositoryInterface $fileRepository */ | |
$fileRepository = \Drupal::service('file.repository'); | |
$fileRepository->writeData($data, $file_path, FileSystemInterface::EXISTS_REPLACE); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Check if a file exists. | |
$destination = '/folder/my_file.pdf'; | |
// PHP code | |
if (!file_exists($destination)) { | |
} | |
// Drupal code | |
/** @var \Drupal\Core\File\FileSystemInterface $file_system */ | |
$file_system = \Drupal::service('file_system'); | |
if ($file_system->getDestinationFilename($destination, \Drupal\Core\File\FileSystemInterface::EXISTS_ERROR)) { | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Drupal\media\Entity\Media; | |
// Load by ID | |
$media = Media::load($media_id); | |
// Load by ID - with no use section. | |
$media = \Drupal\media\Entity\Media::load($media_id); | |
// Util functions | |
private function get_media_url_from_mid($media_id) { | |
$url = NULL; | |
$media = \Drupal\media\Entity\Media::load($media_id); | |
if (isset($media)) { | |
$fid = $media->getSource()->getSourceFieldValue($media); | |
$file = \Drupal\file\Entity\File::load($fid); | |
$uri = $file->getFileUri(); | |
$url = \Drupal::service('file_url_generator')->generateString($uri); | |
} | |
return $url; | |
} | |
private function render_media($media_id) { | |
$media = \Drupal\media\Entity\Media::load($mid); | |
if (!empty($media)) { | |
$builder = \Drupal::entityTypeManager()->getViewBuilder('media'); | |
$rendered_media = $builder->view($media, 'default'); | |
} | |
return $rendered_media ?? NULL; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment