Upload file su dung Form API

Mot thi du ve cach su dung form API de upload file.

  • Ten module: demo
  • Dinh nghia quyen han:
    <?php
    function demo_perm () {
      return array(
    'demo-demo');
    }
    ?>
  • Dinh nghia thao tac:
    <?php
    function demo_menu () {
      return array(
        array(
          
    'path' => 'demo',
          
    'title' => 'Demo title',
          
    'access' => user_access('demo-demo'),
          
    'callback' => 'drupal_get_form',
          
    'callback arguments' => 'demo_demo'
        
    )
      );
    }
    ?>
  • Dinh nghia form:
    <?php
    function demo_demo () {
      return array(
        
    'file' => array(
          
    '#type' => 'file',
          
    '#title' => 'My file'
        
    ),
        
    'submit' => array (
          
    '#type' => 'submit',
          
    '#value' => ' Do submit'
        
    ),
        
    '#attributes' => array(
          
    'enctype' => 'multipart/form-data'
        

      );
    }
    ?>
  • Kich ban validate buoc nguoi dung submit mot file:
    <?php
    function demo_demo_validate ($form_id$form_values) {
      if (!
    file_check_upload('file')) {
        
    form_set_error ('file''Have to upload a file.');
      }
    }
    ?>
  • Luu file upload vao folder files:
    <?php
    function demo_demo_submit ($form_id$form_values) {
      
    $file file_check_upload('file');
      
    file_save_upload ($file'edited-'.$file->filename);
    }
    ?>

Chu y: form element dang file khong chap nhan thuoc tinh #required, neu #required duoc thiet lap la TRUE, he thong se luon tra ve loi khi nguoi dung de trinh.

O Drupal 6, file_check_upload da duoc gop chung voi file_save_upload. Chi tiet xem tai: drupal site

The Hong,