为什么我的文件上传不能在Drupal 7中运行?

时间:2012-03-13 22:40:17

标签: drupal drupal-7

我有一个自定义模块,我想要一个字段来上传图片。 Chrome似乎上传了该文件,但它无效,我收到以下错误。有人可以指出我正确的方向吗?

function nafa_adoption_form($form_state)
{
  $form['#attributes'] = array('enctype' => "multipart/form-data");

  ...

  $form['picture'] = array(
    '#type' => 'file',
    '#title' => t('Picture'),
    '#size' => 20,
    '#upload_location' => 'public://uploads'
  );

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save'),
  );




  return $form;
}

提交功能:

function nafa_adoption_form_submit($form, &$form_state) 
{


  dvm($form_state['values']); //field 'picture' is blank

  $file = file_load($form_state['values']['picture']);

  $file->status = FILE_STATUS_PERMANENT;

  file_save($file);

  $fileid = file_load($file);

  variable_set('adoption_picture', $fileid->uri);

  if ($file)
  {
    drupal_set_message("File uploaded ");
  }

  else
  {
    drupal_set_message("File could not be uploaded");
  }

  drupal_set_message(t('Your form has been saved.'));
}

我也收到以下错误:

Notice: Undefined property: stdClass::$uri in file_save() (line 573 of /home/amn7940/nafa.achristiansen.com/includes/file.inc).

1 个答案:

答案 0 :(得分:1)

如果您查看docs for the file element type,您会注意到没有#upload_location属性。这是因为当使用file类型时,您需要自己将临时文件移动到永久位置。

根据您在提交功能中使用的代码,我非常确定您正在寻找managed_file类型。如果您使用它,您的代码应该开始完美运行:

$form['picture'] = array(
  '#type' => 'managed_file',
  '#title' => t('Picture'),
  '#size' => 20,
  '#upload_location' => 'public://uploads'
);