I'm trying to update the user avatar in my custom module. Which method shall I use to update the image in db as well as to move the file to public directory?


  • The user_picture field installed by the standard profile is an image field. If this is what is on your site, then normal Entity API and File API operations can be done. – mradcliffe Apr 13 '16 at 11:35
  • When using file_save_data() ,what should be given as the first parameter? As shown here (api.drupal.org/api/drupal/core!modules!file!file.module/…) the parameter should be string $data: A string containing the contents of the file. Is this the id of the file type? – wilNev Apr 14 '16 at 9:32

The file gets stored to file_managed table like this:

// Programmatically create files.
use Drupal\file\Entity\File;
$file = File::create([
  'uid' => 1,
  'filename' => $_FILES['file_id']['name'],
  'uri' => 'public://pictures/' . $_FILES['file_id']['name'],
  'status' => 1,

And I manually updated user__user_picture table which is referring to the fid in the above table.

Finally I ended up with move_uploaded_file to store the image to the filesystem. I'll proceed with this approach until I find a better way to do the same.


  • 1
    This working form me $user = user_load(\Drupal::currentUser()->id()); $user->set('user_picture', $file); $user->save(); – Unnikrishnan Sep 3 '16 at 10:19
$user = \Drupal\user\Entity\User::load($uid);
$user->set('user_picture', $fid);
  • I have used the above code and its working fine for me. There is no need of file library use Drupal\file\Entity\File; to update user picture. Simply load the user by their uid and pass the fid or form file upload id in above code. It will automatically update the user profile picture. – Manav Jan 22 '18 at 12:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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