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? 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

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. 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
4

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()); Commented Feb 12, 2021 at 17:34
  • Also, file_move is also deprecated. Use the function "move" from Drupal\file\FileRepositoryInterface (with dependency injection). Commented 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.

0

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:

<?php 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. $file->setFilename($sanitizedFilename); $file->setFileUri($sanitizedFileUri); } } 

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.