Upload file sử dụng Form API

Một thí dụ về cách sử dụng form API để upload file.

  • Tên module: demo
  • Định nghĩa quyền hạn:
    <?php
    function demo_perm () {
      return array(
    'demo-demo');
    }
    ?>
  • Định nghĩa thao tác:
    <?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'
        
    )
      );
    }
    ?>
  • Định nghĩa 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'
        

      );
    }
    ?>
  • Kịch bản validate buộc người dùng submit một file:
    <?php
    function demo_demo_validate ($form_id$form_values) {
      if (!
    file_check_upload('file')) {
        
    form_set_error ('file''Have to upload a file.');
      }
    }
    ?>
  • Lưu file upload vào folder files:
    <?php
    function demo_demo_submit ($form_id$form_values) {
      
    $file file_check_upload('file');
      
    file_save_upload ($file'edited-'.$file->filename);
    }
    ?>

Chú ý: form element dạng file không chấp nhận thuộc tính #required, nếu #required được thiết lập là TRUE, hệ thống sẽ luôn trả về lỗi khi người dùng đệ trình.

Drupal 6, file_check_upload đã được gộp chung với file_save_upload. Chi tiết xem tại: drupal site

Thế Hồng,