Upload an image to filesystem, rename it and set it as Profile Picture for current user

drupal.stackexchange https://drupal.stackexchange.com/questions/294037

  •  25-02-2021
  •  | 
  •  

Question

I have the external link of an image where I am trying to:

  1. Upload the image to filesystem.
  2. Rename the image.
  3. Set the owner of the image to current user.
  4. Set the image as Profile Picture for current user.

So far I have:

$full_name = "John Smith";
$picture_url = "https://scontent.fbey14-1.fna.fbcdn.net/v/t31.0-8/14054356_124897527960923_50194821455451882_o.jpg?_nc_cat=106&_nc_sid=09cbfe&_nc_ohc=P4i5oscJf0IAX_KFCfR&_nc_ht=scontent.fbey14-1.fna&oh=c13b6b2d8712db359f3be5e1ec835340&oe=5EF2B1A4";

// Download the picture to local filesystem.
$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

// Get the Profile Pic ID.
$profile_pic_id = $profile_pic->id();

// Load the image.
$picture = \Drupal\file\Entity\File::load($profile_pic_id);

// Rename the image.
$picture->setFilename("$full_name.jpg");
// Set the owner of the profile picture file.
$picture->setOwner($current_user);

// Save the image.
$picture->save();

$current_user->set('user_picture', $profile_pic_id);
$current_user->save();

The image is indeed uploaded to filesystem under public://profile-pictures, also is successfully set as profile picture of the current user.

and the filename of the image at /user/*/edit edit page is set to: john-smith.jpg, however, the filename of the image at public://profile-pictures is 14054356_124897527960923_50194821455451882_o.jpg while I am expecting it to be john-smith.png !

How to rename the image at the filesystem ?

and does $picture->setOwner($current_user) will set the owner of the image to the current user ?

Was it helpful?

Solution

I agree with @Clive you can do it that why, and also you can download the image directly with the full_name.
To do so just change the line:

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures", TRUE, FILE_EXISTS_REPLACE);

by

$profile_pic = system_retrieve_file($picture_url, "public://profile-pictures/$full_name.jpg", TRUE, FILE_EXISTS_REPLACE);

and remove the line:

$picture->setFilename("$full_name.jpg");

OTHER TIPS

setFilename just updates the field value on the file entity, it doesn't move anything on disk. You can do both in one go with file_move():

$dest = "public://profile-pictures/$full_name.jpg";
if (file_move($picture, $dest) === FALSE) {
  // Something went wrong.
}
Licensed under: CC-BY-SA with attribution
Not affiliated with drupal.stackexchange
scroll top