【问题标题】:Valid extensions for the upload field on Drupal 7Drupal 7 上上传字段的有效扩展
【发布时间】:2011-12-01 02:28:29
【问题描述】:

我需要制作一个表格来上传 CSV 文件。当我尝试使用下面的表单项时出现以下错误:

只允许具有以下扩展名的文件:jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp.

  $form['data_file'] = array(
    '#type' => 'file',
    '#title' => t('Data File'),
    '#description' => t('CSV file to upload.'),
    '#upload_validators' => array(
      'file_validate_extensions' => array('csv'),
      'file_validate_size' => array(32*1024*1024),
    ),
  );

如何让 CSV 文件通过验证器?

【问题讨论】:

    标签: drupal drupal-7


    【解决方案1】:

    你的表单函数

    // don't forget this line
    $form['#attributes'] = array('enctype' => "multipart/form-data");
    
    $form['container']['csv_file'] = array(
    '#type' => 'file' ,  
    '#title' => t('csv FILE') , 
    '#description' => t('insert your csv file here') , 
    ) ; 
    

    你的验证函数

    function _your_function_validate($form, $form_state) {
    $extensions = 'csv' ; 
    $validators = array(
     'file_validate_extensions' => array($extensions),
    );
    // if the file not uploaded or the extension is wrong set error
    if(!file_save_upload('csv_file', $validators)) { // cvs_file is the form name
      form_set_error('csv_file', 'Please select the csv file') ;    
    }else{ 
    // now the form is uploaded lets make another validation for extension
      $file = file_save_upload('csv_file', $validators, file_directory_path()) ; 
    
    // another validator for the extension
    if($file->filemime != 'text/csv' ) {
     form_set_error('csv_file', 'Extensions Allowed : csv') ;       
    }       
    }       
    }
    

    【讨论】:

    • 请注意,在 D7 中,您不需要表单中的 enctype 属性。 Drupal 会自动为您添加文件字段。
    【解决方案2】:

    如果您查看The forms API reference,此评论说明了如何操作。

    我不能完全测试出来,但可能是这样的

      $form['data_file'] = array(
        '#type' => 'file',
        '#title' => t('Data File'),
        '#description' => t('CSV file to upload.'),
        '#upload_validators' => array(
          'file_validate_extensions' => array(0 => 'csv'),
          'file_validate_size' => array(32*1024*1024),
        ),
      );
    

    【讨论】:

    • 我在那边看不到你的 file_validate_extensions 实现。
    • $form['file']['#upload_validators']['file_validate_extensions'][0] = 'png jpg gif pdf';这只是页面上的几行。
    • 您编辑了您的帖子。你有数组('0' => 数组('csv'))。你现在所拥有的正是我原来的版本所创造的。
    • 现在我想了想,它会自动转到数组的索引 0。因此,这将与您最初发布的内容相同。我刚刚又编辑了一遍。如果这不起作用,我不知道。
    【解决方案3】:

    我可以在表单验证钩子中使用以下代码来做到这一点。

    function mymodule_myform_validate($form, $form_state) {
      $validators = array('file_validate_extensions' => array('csv'));
      $file = file_save_upload('zipdata_file', $validators);
      ...
    }
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-05
    相关资源
    最近更新 更多