Drupal 7上的上传字段的有效扩展

时间:2011-10-04 23:54:41

标签: drupal drupal-7

我需要制作一个表单来上传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文件通过验证器?

3 个答案:

答案 0 :(得分:4)

我能够在表单验证钩子中使用以下代码来完成它。

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

答案 1 :(得分:1)

如果您查看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),
    ),
  );

答案 2 :(得分:0)

您的表单功能

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