I had this issue where the generic thumbnail of a media item of type file had gone missing. Because this was a multisite installation, I had to automatically find a solution. Here is how I did it:
The error it produced:
The specified file '/sites/default/files/media-icons/generic/generic.png' could not be copied because the destination directory '' is not properly configured. This may be caused by a problem with file or directory permissions.
Solution
This error occurs because the destination directory does not exist or is not writable. To resolve this issue, you can create the destination directory and ensure it has the proper permissions
use Drupal\Core\File\FileSystemInterface;
/**
* Copy the generic placeholder image to the public files directory.
*/
function vito_update_9070() {
// Get the file_system service.
$file_system = \Drupal::service('file_system');
// Get the real path of the source image in the core media module.
$source = $file_system->realpath('core/modules/media/images/icons/generic.png');
// Get the URI for the destination in the public files directory.
$destination_directory = 'public://media-icons/generic';
$destination = $destination_directory . '/generic.png';
// Check if the destination directory exists, and if not, create it.
if (!is_dir($file_system->realpath($destination_directory))) {
// Prepare the directory with proper permissions.
if (!$file_system->prepareDirectory($destination_directory, FileSystemInterface::CREATE_DIRECTORY)) {
throw new \Exception('Could not create the destination directory.');
}
}
// Copy the source image to the destination and replace the existing file if it exists.
if (!$file_system->copy($source, $destination, FileSystemInterface::EXISTS_REPLACE)) {
throw new \Exception('Could not copy the generic placeholder image to the destination directory.');
}
}
Cheers!