I want to rename an up-loaded file. I have the following code. I have defined a submit handler to do so.

function example_form_submit(&$form, FormStateInterface $form_state) {
    if ($form_state->hasFileElement()) {

        $video_file_file_array = $form_state->getValue('field_video_file');        
        if (is_array($video_file_file_array)) {
            if (isset($video_file_file_array[0])) {
                $video_file_file_id = $video_file_file_array[0]['fids'][0];
                    $file = \Drupal\file\Entity\File::load($video_file_file_id);
                    $file->set('filename', 'something');


This is not working. Is there any other way.

  • Did you debug this at all?
    – Kevin
    Commented Jul 25, 2017 at 0:18
  • @Kevin, the form id that I had the condition for was wrong. Thanks. Commented Jul 25, 2017 at 5:30

4 Answers 4


Your implementation should work. I suspect that for some or other reason the execution just doesn't pass all the conditions you have there which looks a bit weird. Here is an example from my project:

$fid = $form_state->getValue(['field_video_file', 0]);
if (!$form_state->getErrors() && !empty($fid)) {
  try {
    $file = \Drupal\file\Entity\File::load($fid);
  catch (\Exception $e) {
    watchdog_exception('myerror', $e);
  • 1
    This changes the file name in database. Can we rename the actual file before saving it in public directory.
    – Amit
    Commented Mar 27, 2018 at 5:24
  • 1
    @Amit I think you need to make usage of "setFileUri" method. Check the core for usage examples. Commented Mar 27, 2018 at 9:57

Renaming file entity in Drupal 8 can be achieved like this:

    $file = File::load($file_target_id);
    $new_filename = "filename.png";
    $stream_wrapper = \Drupal::service('file_system')->uriScheme($file->getFileUri());
    $new_filename_uri = "{$stream_wrapper}://{$new_filename}";
    file_move($file, $new_filename_uri);

As you can see in this example Drupal file_move function is used here which takes care of everything. You only need to know file target_id which is the file fid.

  • 1
    This is the way to go. Drupal 9 deprecated \Drupal::service('file_system')->uriScheme so in D9 use this instead: $stream_wrapper = \Drupal::service('stream_wrapper_manager')->getScheme($file->getFileUri());
    – LunkRat
    Commented Feb 12, 2021 at 17:34
  • Also, file_move is also deprecated. Use the function "move" from Drupal\file\FileRepositoryInterface (with dependency injection).
    – rsych
    Commented Sep 6, 2022 at 11:27

I had to allow users to upload a file then rename it and erase existing with same name. In a way to have always only on file on the folder which always have the same path.

I try $file->setFilename and $file->setFileUri but these only change the name and url for Drupal (in database) but not the real file (on the server) name. That's why I had to add a specific piece of code to rename it using drupal/php function.

Maybe I should not have to do it because of bad configuration but it works for me.

// In this variable you will have file entity 
$file = \Drupal::entityTypeManager()->getStorage('file')
if (!$file)

$exUri  = explode('/', $file->getFileUri());
$rename = file_unmanaged_move($file->getFileUri(), implode('/', $exUri) . '/' . self::FILE_NAME . '.csv', FILE_EXISTS_REPLACE);

if ($rename) { ... }

If you also want to change the file uri and name to let Drupal know it, just add these lines :

$file->setFileUri(self::FILE_URI . self::FILE_NAME . '.csv');

In my case I had no needs for that.


I needed a similar solution, but to capture all uploaded files and rename them. In this case to remove special characters. This can be done with the solution below:


use Drupal\file\FileInterface;

 * Implements hook_file_presave().
function general_file_presave(FileInterface $file) {
  // Get the filename and file URI.
  $filename = $file->getFilename();
  $fileUri = $file->getFileUri();

  // Sanitize the filename by removing special characters.
  $sanitizedFilename = preg_replace('/[^\w\-\.]/', '', $filename);

  // If the filename has changed, rename the physical file on disk.
  if ($filename !== $sanitizedFilename) {
    // Get the directory part of the file URI.
    $directory = dirname($fileUri);

    // Build the new file URI with sanitized filename.
    $sanitizedFileUri = $directory . '/' . $sanitizedFilename;

    // Rename the physical file on disk.
    /** @var \Drupal\Core\File\FileSystem $fileSystem */
    $fileSystem = \Drupal::service('file_system');

    $fileSystem->move($fileUri, $sanitizedFileUri);

    // Update the filename and file URI in the file entity.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.