Search code examples
drupal-6drupal-fapi

Drupal 6 File Handling


I am handling file upload field in a form using Drupal 6 form APIs. The file field is marked as required. I am doing all the right steps in order to save and rename files in proper locations.

upload form

$form = array();
....
$form['image'] = array(
    '#type' => 'file',
    '#title' => t('Upload photo'),
    '#size' => 30,
    '#required' => TRUE,
);
$form['#attributes'] = array('enctype' => "multipart/form-data");
...

form validate handler

$image_field = 'image';

if (isset($_FILES['files']) && is_uploaded_file($_FILES['files']['tmp_name'][$image_field])) {
    $file = file_save_upload($image_field);
    if (!$file) {
        form_set_error($image_field, t('Error uploading file'));
        return;
    }
    $files_dir = file_directory_path();
    $contest_dir = 'contest';

    if(!file_exists($files_dir . '/' . $contest_dir) || !is_dir($files_dir . '/' . $contest_dir))
        mkdir($files_dir . '/' . $contest_dir);


    //HOW TO PASS $file OBJECT TO SUBMIT HANDLER
    $form_state['values'][$image_field] = $file;
    file_move($form_state['values'][$image_field], $files_dir."/" . $contest_dir . "/contest-". $values['email']. "-" . $file->filename);
}
else {
    form_set_error($image_field, 'Error uploading file.');
    return;
}

On submiting form

Form always reports an error Upload photo field is required. although files are getting uploaded. How to deal with this issue?

How to pass file information to submit handler?


Solution

  • your handler is wrong. You never should touch $_FILES or $_POST variables in drupal, instead you should only use the drupal tools. Said that, the implementation you should is like that:

    function my_form_handler(&$form,&$form_state){/** VALIDATION FILE * */
     $extensions = 'jpeg jpg gif tiff';
     $size_limit = file_upload_max_size(); 
     $validators = array(
          'my_file_validate_extensions' => array($extensions),
          'my_file_validate_size' => array($size_limit),
      );
    
     $dest = file_directory_path();
     if ($file = file_save_upload('image', $validators, $dest)) {
      //at this point your file is uploaded, moved in the files folder and saved in the DB table files
     }
    }