В drupal 6, Как обработать загруженный файл более чем за один шаг? - PullRequest
1 голос
/ 23 сентября 2011

Я пишу пользовательский модуль в drupal.
Цель:

1. Upload a csv file
2. Display its content in a tabular layout.
3. On confirmation, save it in database.

Проблема, с которой я сталкиваюсь:

  1. Я не могу загрузить ни один файл. Я не получаю ничего в $ _FILES, даже если я загружаю или нет. >> решено
  2. Как мне разделить процесс? Предположим, мне удалось загрузить файл [действительно с вашей помощью;)], и я сохраняю файл, предположим, в каталоге drupal6 / uploaded_data. Как мне перенаправить на следующую страницу, где я могу прочитать из файла и показать табличные данные для подтверждения.

Коды :)
хуки меню и все

function productsadmin_menu() {
    $items['admin/settings/product-administration'] = array(
        'title' => 'Product Administration',
        'description' => 'Upload products data',
        'page callback' => 'productsadmin_form',
        'access arguments' => array('access content'),
        'type' => MENU_NORMAL_ITEM,
    );
    return $items;
}

function productsadmin_form() {
    return drupal_get_form('productsadmin_my_form');
}

Эта функция передается drupal_get_form()

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

  $form['csv'] = array(
    '#type' => 'file',
    '#title' => 'Product Catalog',
    '#description' => 'Product catalog in specified csv format',
    '#required' => FALSE,
  );
  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => 'Submit',
  );
  return $form;
}

Проверка (часть, которая не работает, комментируется)

function productsadmin_my_form_validate($form, &$form_state) {
    if($form_state['values']['csv'] == "") {
        form_set_error('csv', t('Please input product catalog csv data'));
    }

/*  // Check if file is uploaded (Not working)
    if ($_FILES['files']['name']['csv'] == '') {
        form_set_error('csv', t('Please upload product catalog' . $rahul_vals));
    }
*/
}

Отправить действие

function productsadmin_my_form_submit($form, &$form_state) {
    /*
        1. Move File to uploaded_dir
        2. Change the header so that it is redirected to new page
    */
}

1 Ответ

2 голосов
/ 25 сентября 2011

вы не должны использовать $_FILES в drupal, используйте drupal api

Я сделал этот пример, чтобы вы объяснили, как работать с cvs

   /**
    * Form function  
    */
     function _form_cvs_import($form_state) {
      $form['#attributes'] = array('enctype' => "multipart/form-data");
      $form['container'] = array(
        '#type' => 'fieldset', 
        '#title' => t('CVS UPLOAD') , 
      );
      $form['container']['cvs_file'] = array(
        '#type' => 'file' ,  
        '#title' => t('CVS FILE') , 
        '#description' => t('insert your cvs file here') , 
      ) ;   
      $form['container']['submit'] = array(
        '#type' => 'submit' ,  
        '#value' => t('SEND') , 
      ) ;       

       return $form ; 
    }

/**
* form validate
*/
function _form_cvs_import_validate($form, $form_state) {
 $validators = array(
  'file_validate_extensions' => array('cvs'),
 );
 if(!file_save_upload('cvs_file', $validators)) { // the file is not submitted
    form_set_error('cvs_file', 'Please select the cvs file') ;  
 }else{ // the file is submitted another validation for extension
   $file = file_save_upload('cvs_file', $validators, file_directory_path()) ; 
   if($file->filemime != 'application/octet-stream' ) {
     form_set_error('cvs_file', 'Extensions Allowed : cvs') ;       
   }        
 }      
}


/**
*  form submit
*/
function _form_cvs_import_submit($form, $form_state) {
    $file = file_save_upload('cvs_file', $validators, file_directory_path()) ;  // this is the cvs file in the tmp directory
    $file_handler = fopen($file->filepath, 'r') ; // open this cvs file
    $line_num = 0 ;
    $fields = array() ;  
    while(!feof($file_handler)) { 
        $line_num++ ; 
        $line = fgets($file_handler) ; // this is the line/row
        $line_array = explode(",", $line);  //  array of row fields
        $field_num = 0 ;  
        foreach($line_array as $field) { 
            $field_num++ ; 
            $fields[$line_num][$field_num] = str_replace('"', '', $field );  // E.g you can access second row and third field by $fields[2][3]
        }   
    }
    fclose($file_handler);
    unlink($file->filepath);
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...