问题描述
我找到了这个脚本 http://d.danylevskyi.com/node/7我已将其用作以下代码的入门.
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);
}
?>
在sites/default/files/pictures/中创建了一张图片,名称为picture-99-1362753611.gif
A picture is created in sites/default/files/pictures/ with the name picture-99-1362753611.gif
file_managed 表中的一切似乎都是正确的,除了:
Everything seems correct in the file_managed table except that:
- 文件名字段为空
- uri 字段显示 public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif
- 状态字段设置为 0(临时)
users 表中的图片字段使用上述条目的 fid 进行更新.
The picture field in the users table gets updated with the fid of the above mentioned entry.
我猜 file_managed 表应该存储最终文件(在站点/默认/图片中)而不是原始文件信息,并且用户表也应该链接到那个.
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.
知道如何实现这一目标吗?我对 Drupal API 很陌生.谢谢.
Any idea how I can achieve that? I am quite new to the Drupal API. Thank you.
我知道我将原始文件提供给 file_save 和 user_save 函数.但是哪个实际上在sites/default/pictures/中创建了文件?
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/ ?
推荐答案
尝试将以下内容添加到您的代码中:
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
这有帮助吗?
------------------- 编辑 ------------------
------------------ 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://');
这篇关于Drupal 7 以编程方式保存用户图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!