使用Form API上传后预览图片


9

我使用managed_fileForm API类型上传了图像文件,但上传图像后,该文件未显示为该字段旁边的缩略图。呈现的是图像的文件名,带有指向图像的链接和一个小图标。

上传图像后如何显示图像的缩略图(如来自核心“图像”字段的图像预览)?

另外,如何在其旁边显示默认图像(如果具有默认值)?

这是我的代码:

$form['logo'] = array(
      '#title' => t('Logo'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#default_value' => variable_get('logo', ''),
      '#upload_location' => 'public://',
      '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(0.3*1024*1024),
  )

Answers:


4

我已通过一个简单的解决方法解决了该问题。您可以将一个主题添加到表单元素“ tbs_thumb_upload”,然后在主题文件中将主题文件中提到的元素添加到手。

 // THIS IS THE FILE FIELD  
 $form['logo'] = array(
  '#type' => 'managed_file',
  '#title' => t('Logo'),
  '#description' => t('Allowed extensions: gif png jpg jpeg'),
  '#upload_validators' => array(
    'file_validate_extensions' => array('gif png jpg jpeg'),
    // Pass the maximum file size in bytes
    'file_validate_size' => array(1 * 1024 * 1024),
  ),
  '#theme' => 'tbs_thumb_upload',
  '#upload_location' => 'public://society/',
  '#attributes' => array('default_image_path' => TBS_IMAGE_DEFAULT_SOCIETY)
  );

 // THIS IS THE THEME FILE : THEME : tbs_thumb_upload : Theme file code
 if (!empty($form['#file'])) {
   $uri = $form['#file']->uri;
   $desc = FALSE;
 }else {
   $uri = $form['#attributes']['default_image_path'];
   $desc = TRUE;
 }

 // Render form element
 print drupal_render_children($form);

1
代码的最后一部分是否可以从if (!empty($form['#file'])) {`print drupal_render_children($ form);`写入.tpl.php文件中?如果没有,那我该在哪里写?
Subhajyoti 2014年

9

在字段中定义主题,并模拟代码结构以预览刚刚上传的图像。我的解决方法如下

$form['abc_field']['abc_filename'] = array(
        '#type' => 'managed_file',
        '#title' => t('abc image'),
        '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(1 * 1024 * 1024),
        ),
        '#theme' => 'abc_thumb_upload',
        '#upload_location' => 'public://abc/'
    );

在您的hook_theme()中,

return array(
    'abc_thumb_upload' => array(
        'render element' => 'element',
        'file'           => 'abc.module',
));

在您的theme_abc_thumb_upload()中,

function theme_abc_thumb_upload($variables) {

    $element = $variables['element'];

    if (isset($element['#file']->uri)) {
        $output = '<div id="edit-logo-ajax-wrapper"><div class="form-item form-type-managed-file form-item-logo"><span class="file">';
        $output .= '<img height="50px" src="' . file_create_url($element['#file']->uri) . '" />';
        $output .= '</span><input type="submit" id="edit-' . $element['#name'] . '-remove-button" name="' . $element['#name'] . '_remove_button" value="Remove" class="form-submit ajax-processed">';
        $output .= '<input type="hidden" name="' . $element['#name'] . '[fid]" value="' . $element['#file']->fid . '">';

        return $output;
    }
}

3
最好用image_style_url('thumbnail', $element['#file']->uri)它代替file_create_url($element['#file']->uri)-如果用户上传错误的内容,当前代码可能会严重破坏布局。
Mołot

这里有一个非常类似的解决方案:stackoverflow.com/questions/18997423/…–
ognockocaten

4

关于尺寸,请检查以下验证file_validate_image_resolution

$form['logo'] = array(
      '#title' => t('Logo'),
      '#type' => 'managed_file',
      '#required' => TRUE,
      '#default_value' => variable_get('logo', ''),
      '#upload_location' => 'public://',
      '#upload_validators' => array(
            'file_validate_extensions' => array('gif png jpg jpeg'),
            'file_validate_size' => array(0.3*1024*1024),
            'file_validate_image_resolution'=>array('100x100'),
  )

3

修改HTML的“删除”按钮对我不起作用。页面刷新而不删除图像。相反,我从中找到的核心图片字段的theme_image_widget回调中复制了内容docroot/modules/image/image.field.inc

/**
* Implements theme_mymodule_thumb_upload theme callback.
*/
function theme_mymodule_thumb_upload($variables) {
  $element = $variables['element'];
  $output = '';
  $output .= '<div class="image-widget form-managed-file clearfix">';

  // My uploaded element didn't have a preview array item, so this didn't work
  //if (isset($element['preview'])) {
  //  $output .= '<div class="image-preview">';
  //  $output .= drupal_render($element['preview']);
  //  $output .= '</div>';
  //}

  // If image is uploaded show its thumbnail to the output HTML
  if ($element['fid']['#value'] != 0) {
    $output .= '<div class="image-preview">';

    // Even though I was uploading to public:// the $element uri was pointing to temporary://system, so the path to the preview image was a 404
    //$output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => file_load($element['fid']['#value'])->uri, 'getsize' => FALSE));

    $output .= theme('image_style', array('style_name' => 'thumbnail', 'path' => 'public://'.$element['#file']->filename, 'getsize' => FALSE));
    $output .= '</div>';
  }

  $output .= '<div class="image-widget-data">';

  if ($element['fid']['#value'] != 0) {
    $element['filename']['#markup'] .= ' <span class="file-size">(' . format_size($element['#file']->filesize) . ')</span> ';
  }

  // The remove button is already taken care of by rendering the rest of the form. No need to hack up some HTML!
  $output .= drupal_render_children($element);

  $output .= '</div>';
  $output .= '</div>';

  return $output;
}

使用此主题功能来渲染元素:

/**
* Implements hook_theme().
*/
function mymodule_theme() {
  return array(
    'mymodule_thumb_upload' => array(
      'render element' => 'element',
    )
  );
}

表单元素定义:

$form['upload_image'] = array(
  '#type' => 'managed_file',
  '#default_value' => $value,
  '#title' => t('Image'),
  '#description' => t('Upload an image'),
  '#upload_location' => 'public://',
  '#theme' => 'mymodule_thumb_upload',
  '#upload_validators' => array(
    'file_validate_is_image' => array(),
    'file_validate_extensions' => array('jpg jpeg gif png'),
    'file_validate_image_resolution' => array('600x400','300x200'),
  ),
);

这应该是答案,最后ajax起作用了,谢谢!!!
DarkteK '18

2

添加另一个表单元素以包含图像预览的标记。在下面的代码中,$ v包含感兴趣的表单值。您的特定情况可能会将它们从节点,表单状态或其他位置拉出。它是转换为数组的文件对象。

// If there is a file id saved
if (!empty($v['fid'])) {
  // If there is no file path, a new file is uploaded
  // save it and try to fetch an image preview
  if (empty($v['uri'])) {
    $file = file_load($v['fid']);
    // Change status to permanent so the image remains on the filesystem. 
    $file->status = FILE_STATUS_PERMANENT;
    $file->title  = $v['title'];
    // Save.
    file_save($file);
    global $user;
    file_usage_add($file, 'node', 'node', $user->uid);
    $v = (array)$file;
  }
  $form['photos']['items'][$i]['preview']['#markup'] = theme(
    'image_style',
    array(
      'style_name' => 'form_image_preview',
      'path' => file_build_uri(file_uri_target($v['uri']))
    )
  );
}

请注意,我将文件状态设置为永久并重新保存。这是为了使上传的图像正确预览。无法为临时存储中的图像生成图像样式,因此必须将其标记为烫发。根据您的用例和工作流程,您可能必须处理“孤立”图像。

我的表单结构($ form ['photos'] ['items'] [$ i])用于多输入图像字段。我有一个主题模板,可将它们收集起来并放在drupal_add_tabledrag中。您的表单数组结构可能会有所不同。


谢谢杰森,但我认为这是万一我有数据并想以以下形式查看的时候(我认为$ v是具有图像uri的对象)我想像在图像字段中那样预览图像当使用字段旁边的“上传”按钮上传图像时,它会出现在字段旁边
Ahmed

这就是我在这里所做的。$ v是表单项的值。在AJAX / AHAH刷新期间,将重新生成表单,该值将用于在新上传的文件旁边显示预览图像。$ form ['photos'] ['items']是将“预览”和文件上传小部件“分组”的包装器。$ form ['photos'] ['items'] [x] ['photo']将是您的小部件。
杰森·史密斯

我没有使用AHAH(只是Drupal 7表单api),并且正在上载刷新所有表单
Ahmed

我知道没有办法不使用AJAX / AHAH,对不起,我无法提供更多帮助:/
Jason Smith
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.