2010-01-03 70 views
5

由於某些原因,當我嘗試進行文件上傳時,表單會中斷。下面是它的代碼:Drupal:需要上傳文件嗎?

$form_id = "upload_form"; 

$form[$form_id] = array (
    '#type' => 'fieldset', 
    '#description' => t('This is a utility to import nodes from a Comma Separated Value file. To begin, pick a node type, and upload a CSV.'), 
); 

$form[$form_id]['type'] = array(
    '#title' => t('Enter node type'), 
    '#type' => 'textfield', 
//  '#autocomplete_path' => '', TODO: autocomplete for node types 
    '#required' => TRUE, 
    '#description' => t('This node type should already exist. If it doesn\'t, create it first.'), 
); 

$form[$form_id]['upload'] = array(
    '#type' => 'file', 
    '#title' => t('Upload CSV file'), 
//  '#size' => 40, 
    '#description' => t('This will not work for a non-CSV file.'), 
//  '#required' => TRUE, TODO: breaks it. why? 
); 

$form[$form_id]['submit'] = array(
    '#type' => 'submit', 
    '#value' => t('Submit'), 
); 

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

在一個Drupal支持site,有人說,這是不可能使所需的文件上傳。這是真的?

+0

它是如何突破?你是否收到錯誤信息? – Evert 2010-01-04 09:18:34

+0

即使選擇了上傳文件,也不會讓用戶提交表單。 – 2010-01-04 18:28:03

回答

3

這是我的解決方法,以使文件必填字段:

<?  
    // A piece of form that defines the file field 
    $form['attachment'] = array(
     '#type' => 'file', 
     '#title' => t('Title'), 
     //'#required' => TRUE, // check this manually 
    ); 

    // Form validation hook 
    function yourformname_validate($form, &$form_state) { 
     // Validate file 
     $validators = array(
      'file_validate_extensions' => array('doc txt pdf'), // does not work for user 1 
      'file_validate_size' => array(1000000, 0), 
     ); 
     $file = file_save_upload('attachment', $validators, file_directory_path()); 
     if ($file) { 
      $form_state['values']['attachment'] = $file; // drupal file object 
     } 
     else{ 
      form_set_error('attachment', "File is required"); 
     } 
    } 
?> 
+0

這適用於要求上傳,但它不適當地驗證文件擴展名。我能夠上傳一個JPG。 – 2010-01-07 23:34:12

+0

對不起,你是對的。我修正了這個問題。仍然驗證文件類型不適用於第一個用戶。 – Kniganapolke 2010-01-08 08:24:10

0

我不是Drupal專家,但你可以檢查是否存在$_FILES變量,不是嗎?