By hari, 29 October, 2022 Drupal with Service This would be suitable for .module and .theme file use Drupal\Core\File\FileSystemInterface; // on top use Drupal\file\Entity\File; // on top function SaveFile($data, $destination) { if (!\Drupal::service('file_system')->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) { return FALSE; } \Drupal::service('file_system')->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE); $new_file = File::create(['uri' => $file->uri]); $new_file->setOwnerId(1); $new_file->setPermanent(); $new_file->save(); return $new_file; } Object-oriented way use Drupal\Core\File\FileSystemInterface; // on top use Drupal\file\Entity\File; // on top Class CustomClass { /** * @var \Drupal\Core\File\FileSystemInterface */ protected $fileSystem; /** * @param \Drupal\Core\File\FileSystemInterface $file_system * The file system manager. */ public function __construct(FileSystemInterface $file_system) { $this->fileSystem = $file_system; } public function SaveFile($data, $destination) { if (!$this->fileSystem->prepareDirectory($destination, FileSystemInterface::CREATE_DIRECTORY)) { return FALSE; } $this->fileSystem->saveData($data, $destination, FileSystemInterface::EXISTS_REPLACE); $new_file = File::create(['uri' => $file->uri]); $new_file->setOwnerId(1); $new_file->setPermanent(); $new_file->save(); return $new_file; } } Tags Drupal