【问题标题】:Drupal: File upload required?Drupal:需要上传文件吗?
【发布时间】:2010-01-03 20:13:42
【问题描述】:

由于某种原因,当我尝试要求上传文件时,我的表单会中断。这是它的代码:

$form_id = "upload_form";

$form[$form_id] = array (
    '#type' => 'fieldset',
    '#description' => t('This is a utility to import nodes from a Comma Separated Value file. To begin, pick a node type, and upload a CSV.'),
);

$form[$form_id]['type'] = array(
    '#title' => t('Enter node type'),
    '#type' => 'textfield',
//      '#autocomplete_path' => '', TODO: autocomplete for node types
    '#required' => TRUE,
    '#description' => t('This node type should already exist. If it doesn\'t, create it first.'),
);

$form[$form_id]['upload'] = array(
    '#type' => 'file',
    '#title' => t('Upload CSV file'),
//      '#size' => 40,
    '#description' => t('This will not work for a non-CSV file.'),
//      '#required' => TRUE, TODO: breaks it. why?
);

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

$form['#attributes'] = array('enctype' => 'multipart/form-data');

在 Drupal 支持site 上,有人说不可能要求上传文件。这是真的吗?

【问题讨论】:

  • 它是怎么破的?您收到错误消息了吗?
  • 它不允许用户提交表单,即使选择了要上传的文件。

标签: php drupal-6 file-upload


【解决方案1】:

这是我将文件字段设为必需的解决方法:

<?    
    // A piece of form that defines the file field
    $form['attachment'] = array(
        '#type' => 'file',
        '#title' => t('Title'),
        //'#required' => TRUE,  // check this manually
    );

    // Form validation hook
    function yourformname_validate($form, &$form_state) {
        // Validate file
        $validators = array(
            'file_validate_extensions' => array('doc txt pdf'), // does not work for user 1
            'file_validate_size' => array(1000000, 0),
        );
        $file = file_save_upload('attachment', $validators, file_directory_path());
        if ($file) {
             $form_state['values']['attachment'] = $file; // drupal file object
        }
        else{
             form_set_error('attachment', "File is required");
        }
    }
?>

【讨论】:

  • 这适用于要求上传,但它不能正确验证文件扩展名。我能够上传 jpg。
  • 对不起,你是对的。我已经解决了。文件类型的验证仍然不适用于第一个用户。
【解决方案2】:

我不是 Drupal 专家,但您可以检查 $_FILES 变量是否存在,不是吗?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-30
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 1970-01-01
    • 2011-10-21
    相关资源
    最近更新 更多