drupal模块配置过程上传文件

时间:2011-10-07 16:44:35

标签: drupal drupal-7

如何在模块配置部分处理文件上传?这是我到目前为止所拥有的。

<?php
function dc_staff_directory_admin_settings() 
{
  $form['dc_staff_directory_upload_file'] = array(
    '#type' => 'file',
    '#title' => t('Upload staff directory excel (.xls) file'),
    '#description' => t('Uploading a file will replace the current staff directory'),
  );
  $form['#submit'][] = 'dc_staff_directory_process_uploaded_file';
  return system_settings_form($form);
}

function dc_staff_directory_process_uploaded_file($form, &$form_state)
{
   //What can I do here to get the file data?
}

1 个答案:

答案 0 :(得分:4)

如果您使用managed_file类型,Drupal将为您完成大部分处理,您只需在提交函数中将文件标记为永久存储:

function dc_staff_directory_admin_settings() {
  $form['dc_staff_directory_upload_file'] = array(
    '#type' => 'managed_file',
    '#title' => t('Upload staff directory excel (.xls) file'),
    '#description' => t('Uploading a file will replace the current staff directory'),
    '#upload_location' => 'public://path/'
  );

  $form['#submit'][] = 'dc_staff_directory_process_uploaded_file';
  $form['#validate'][] = 'dc_staff_directory_validate_uploaded_file';
  return system_settings_form($form);
}

function db_staff_directory_validate_uploaded_file($form, &$form_state) {
  if (!isset($form_state['values']['dc_staff_directory_upload_file']) || !is_numeric($form_state['values']['dc_staff_directory_upload_file'])) {
    form_set_error('dc_staff_directory_upload_file', t('Please select an file to upload.'));
  }
}

function dc_staff_directory_process_uploaded_file($form, &$form_state) {
   if ($form_state['values']['dc_staff_directory_upload_file'] != 0) {
      // The new file's status is set to 0 or temporary and in order to ensure
      // that the file is not removed after 6 hours we need to change it's status
      // to 1.
      $file = file_load($form_state['values']['dc_staff_directory_upload_file']);
      $file->status = FILE_STATUS_PERMANENT;
      file_save($file);
   }

}

验证功能也可能是一个好主意,如果文件不是必填字段,显然你不需要它。

这主要来自image_example模块,Examples Module的一部分。如果您真的不想使用managed_file类型查看同一集合中的file_example模块,则会提供有关如何上载非托管文件的示例。

希望有所帮助