image - Drupal 7 - 以编程方式上传图像

标签 image file drupal upload

我想在自定义模块中上传图像。如果需要,必须永久保存图像并重命名。稍后我希望能够在表单上的某处或任何我想要的地方显示图像。

我当前的代码:

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.')
);

 ....
}

在提交 Hook 中,我有:
// 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).'"/>');
//----------------------------  

最佳答案

我最近不得不这样做。这就是我最终得到的。这是在不使用drupal表单的情况下将图像保存到图像字段。

if(isset($_FILES['image'])){

    $node = node_load($nid);

    //Get the uploaded file from the temp directory.            
    $image = file_get_contents($_FILES['image']['tmp_name']);

    //Create the directory if it does not already exist, otherwise check the permissions
    $directory = 'public://my-image-folder';
    file_prepare_directory($directory, FILE_CREATE_DIRECTORY);

    //Saves a file to the specified destination and creates a database entry.
    $file = file_save_data($image, 'public://my-image-folder/'.$_FILES['image']['name'], FILE_EXISTS_RENAME);

    //Set the file status to permanent so it is not deleted in next cron run
    $file->status = FILE_STATUS_PERMANENT;
    file_save($file);

    //Now we have a saved file and an object for it, just need to add it to the node's image field.
    $node->field_my_image_field[$node->language][0] = (array)$file;

    node_save($node);
}

关于image - Drupal 7 - 以编程方式上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8241242/

相关文章:

php - 快速、轻松地裁剪网页图像

php - 如何在不覆盖现有文件的情况下在 PHP 中复制文件?

java - 通过相对路径创建文件不适用于 IDE

linux - 如何在Linux上使用命令行为Drupal安装GD库?

javascript - 如何删除 Drupal 安装时加载的第二个 jquery 库

drupal - 如何使用 hook_menu_alter() 来操作路径访问控制

ios - 让图像 if nil 在 swift 3 中消失(或缩小,使其看起来消失)

javascript - Canvas 图像到图像文件

html - 在单元格中拟合图像

python - 如何将对象成员变量的值写入 csv 行?