Drupal 7: Rename files on upload (via filefield)

Eugene picture Eugene · Dec 16, 2012 · Viewed 9.3k times · Source

I am looking for a way to rename files that are uploaded by users through a filefield. For example, rename user profile photos using uniqid.

I found a good solution for D6 at "Drupal 6: How to Change Filename on Upload" but can't find anything for D7.

Another option is to use File (Field) Paths, but:

  1. The module causes warnings on my setup.
  2. Seems to be a bit of an overkill to install a general module for a very specific purpose.

Answer

Yuseferi picture Yuseferi · Apr 30, 2015

You can change every file upload by hook_file_presave as your desire pattern as example

function yourmodulename_file_presave($file) {
  $parts = pathinfo($file->filename);
  $file->filename = 'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
}

but this method do not rename filname(it just rename file name in file_managed table), if you want also rename file name (uri of file) you should use below code

function hook_file_insert($file) {
  $parts = pathinfo($file->filename);
  $uri = 'public://'.'mypattern_'.$file->uid .'_'. $file->timestamp . '.' . $parts['extension'];
  $file=file_move($file, $uri);
}