2011-11-23 127 views
3

我想上传一个图片在自定义模块中。如果需要,图像必须永久保存并重命名。之后,我希望能够将图像显示在我的表单上或我想要的任何位置。Drupal 7 - 上传图片编程方式

我当前的代码:

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

回答

2

尝试:

$validators = array(
    'file_validate_extensions' => array('jpg png gif'), 
); 
    //Save file 
    if ($file = file_save_upload('icon', $validators, $your_file_destination)) { 
    $file_content = file_get_contents($file->filepath); 
    } 
    else{ 
    form_set_error('icon', 'Could not upload file.'); 
    } 
+0

我不能让它工作。请参阅我在第一篇文章中编辑的示例。我必须以某种方式从输入字段中获取文件,但似乎已经出错了。 – Napoleon

+0

删除file_save_data调用,并且$ dest应该是您的文件将保存在的目录(例如,file_directory_path()是您设置默认文件目录的位置,通常为sites/default/files) – vgardner

+0

file_directory_path()已被删除在D7中,但我找到了替代品。编辑:它现在似乎工作。 – Napoleon

5

我不得不近日做到这一点。这是我最终的结果。即将图像保存到图像字段而不使用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); 
}