function file_save_data

Same name in other branches
  1. 7.x includes/file.inc \file_save_data()
  2. 9 core/modules/file/file.module \file_save_data()

Saves a file to the specified destination and creates a database entry.

Parameters

string $data: A string containing the contents of the file.

string|null $destination: (optional) A string containing the destination URI. This must be a stream wrapper URI. If no value or NULL is provided, a randomized name will be generated and the file will be saved using Drupal's default files scheme, usually "public://".

int $replace: (optional) The replace behavior when the destination file already exists. Possible values include:

Return value

\Drupal\file\FileInterface|false A file entity, or FALSE on error.

See also

\Drupal\Core\File\FileSystemInterface::saveData()

9 calls to file_save_data()
FileFieldWidgetTest::createTemporaryFile in core/modules/file/tests/src/Functional/FileFieldWidgetTest.php
Creates a temporary file, for a specific user.
FileItem::generateSampleValue in core/modules/file/src/Plugin/Field/FieldType/FileItem.php
Generates placeholder field values.
SaveDataTest::testExistingError in core/modules/file/tests/src/Kernel/SaveDataTest.php
Test that file_save_data() fails overwriting an existing file.
SaveDataTest::testExistingRename in core/modules/file/tests/src/Kernel/SaveDataTest.php
Test file_save_data() when renaming around an existing file.
SaveDataTest::testExistingReplace in core/modules/file/tests/src/Kernel/SaveDataTest.php
Test file_save_data() when replacing an existing file.

... See full list

File

core/modules/file/file.module, line 580

Code

function file_save_data($data, $destination = NULL, $replace = FileSystemInterface::EXISTS_RENAME) {
    $user = \Drupal::currentUser();
    if (empty($destination)) {
        $destination = \Drupal::config('system.file')->get('default_scheme') . '://';
    }
    
    /** @var \Drupal\Core\StreamWrapper\StreamWrapperManagerInterface $stream_wrapper_manager */
    $stream_wrapper_manager = \Drupal::service('stream_wrapper_manager');
    if (!$stream_wrapper_manager->isValidUri($destination)) {
        \Drupal::logger('file')->notice('The data could not be saved because the destination %destination is invalid. This may be caused by improper use of file_save_data() or a missing stream wrapper.', [
            '%destination' => $destination,
        ]);
        \Drupal::messenger()->addError(t('The data could not be saved because the destination is invalid. More information is available in the system log.'));
        return FALSE;
    }
    try {
        $uri = \Drupal::service('file_system')->saveData($data, $destination, $replace);
        // Create a file entity.
        $file = File::create([
            'uri' => $uri,
            'uid' => $user->id(),
            'status' => FILE_STATUS_PERMANENT,
        ]);
        // If we are replacing an existing file re-use its database record.
        // @todo Do not create a new entity in order to update it. See
        //   https://www.drupal.org/node/2241865.
        if ($replace == FileSystemInterface::EXISTS_REPLACE) {
            $existing_files = \Drupal::entityTypeManager()->getStorage('file')
                ->loadByProperties([
                'uri' => $uri,
            ]);
            if (count($existing_files)) {
                $existing = reset($existing_files);
                $file->fid = $existing->id();
                $file->setOriginalId($existing->id());
                $file->setFilename($existing->getFilename());
            }
        }
        elseif ($replace == FileSystemInterface::EXISTS_RENAME && is_file($destination)) {
            $file->setFilename(\Drupal::service('file_system')->basename($destination));
        }
        $file->save();
        return $file;
    } catch (FileException $e) {
        return FALSE;
    }
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.