5

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];
                if($video_file_file_id){
                    $file = \Drupal\file\Entity\File::load($video_file_file_id);
                    $file->set('filename', 'something');
                    $file->save();

                }                
            }
        }
    }
}

This is not working. Is there any other way.

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

3 Answers 3

3

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);
    $file->setFilename('smth');
    $file->save();
  }
  catch (\Exception $e) {
    watchdog_exception('myerror', $e);
  }
}
2
  • 1
    This changes the file name in database. Can we rename the actual file before saving it in public directory.
    – Amit
    Mar 27, 2018 at 5:24
  • 1
    @Amit I think you need to make usage of "setFileUri" method. Check the core for usage examples. Mar 27, 2018 at 9:57
5

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.

2
  • 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
    Feb 12, 2021 at 17:34
  • Also, file_move is also deprecated. Use the function "move" from Drupal\file\FileRepositoryInterface (with dependency injection).
    – rsych
    Sep 6, 2022 at 11:27
1

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')
    ->load($form_state->getValue('csv_file')[0]);
if (!$file)
  return;

$exUri  = explode('/', $file->getFileUri());
array_pop($exUri);
$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->setFilename(self::FILE_NAME);
$file->setFileUri(self::FILE_URI . self::FILE_NAME . '.csv');
$file->save();

In my case I had no needs for that.

Your Answer

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

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