【发布时间】:2012-01-04 16:32:22
【问题描述】:
我想在自定义模块中上传图片。如果需要,必须永久保存图像并重命名。稍后我希望能够在表单上的某处或我想要的任何位置显示图像。
我当前的代码:
function my_module_name_new_form()
{
....
$form['icon'] = array
(
'#type' => 'file',
'#title' => t('Icon'),
'#description' => t('Click "Chose File" to select an image to upload.')
);
....
}
在提交钩子中我有:
// Icon
$filename = $form_state['values']['icon'];
$dest = file_build_uri($filename);
file_save_data('My data', $dest, FILE_EXISTS_RENAME);
什么都没有发生...我也找不到任何与 Drupal 7.x 兼容的模块,它们以某种方式让这里的生活更轻松。
解决方案:
//----------------------------
// Icon
//----------------------------
$dest_dir = file_default_scheme() . '://';// Note: file_directory_path() was removed in Drupal 7.x. // $dest_dir contains the destination directory for the file.
$validators = array('file_validate_extensions' => array('jpg png gif'));
//Save file
if ($file = file_save_upload('icon', $validators, $dest_dir))
{
$filename = $file->filename;
$file_content = file_get_contents($dest_dir.$filename); // Fatal error: Cannot access empty property in C:\xampp\htdocs\drupal\modules\custom\achievements\achievements.module on line 446
}
else
{
form_set_error('icon', 'Could not upload file.');
}
// To display the image: // die('<IMG SRC="'.file_create_url($dest_dir.$filename).'"/>');
//----------------------------
【问题讨论】: