Drupal 7 save user picture programmatically

本秂侑毒 提交于 2019-12-21 05:38:15

问题


I have found this script http://d.danylevskyi.com/node/7 which I have used as a starter for the below code.

The goal is to be able to save a user picture:

<?php
define('DRUPAL_ROOT', getcwd());

require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);

$uid = 99;
$account = user_load($uid);

// get image information
$image_path = 'public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif';
$image_info = image_get_info($image_path);

// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];

// standard Drupal validators for user pictures
$validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
    'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);

// here all the magic :) 
$errors = file_validate($file, $validators);
if (empty($errors)) {

    file_save($file);
    $edit['picture'] = $file;
    user_save($account, $edit);
}
?>

A picture is created in sites/default/files/pictures/ with the name picture-99-1362753611.gif

Everything seems correct in the file_managed table except that:

  1. the filename field is empty
  2. the uri field shows public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif
  3. the status field is set to 0 (temporary)

The picture field in the users table gets updated with the fid of the above mentioned entry.

I would guess that the file_managed table should store the final file (in sites/default/pictures) instead of the original file info and that the users table should link to the one too.

Any idea how I can achieve that? I am quite new to the Drupal API. Thank you.

Edit:

I understand that I am giving the original file to the file_save and user_save functions. But which one actually creates the file in sites/default/pictures/ ?


回答1:


Try adding the following to your code:

$file->filename = drupal_basename($image_path);
$file->status   = FILE_STATUS_PERMANENT;
$file = file_save($file);  // Use this instead of your current file_save

Does that help?

------------------ EDIT ------------------

If you want to save a copy of the file in a new location, you can replace the third line above with something like

// Save the file to the root of the files directory.
  $file = file_copy($file, 'public://');


来源:https://stackoverflow.com/questions/15297551/drupal-7-save-user-picture-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!