Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drupal 7 forms API: File upload

I've been following the form example 10 from the Drupal doc: http://api.drupal.org/api/examples/form_example!form_example.module/group/form_example/7

Here goes the definition of my form:

function portal_upload_form($form, $form_state) {

    $form['file'] = array(
        '#type' => 'file',
        '#title' => t('Choose a file'),
    );

    $form['document_submit_button'] = array(

      '#type' => 'submit', 
      '#value' => t('upload'), 
    );

    return $form;
}

And the form_submit hook:

function portal_upload_form_submit($form, &$form_state) {

    $file = $form_state['values']['file'];
        // ...

$file is 'empty' despite having set an input file with 777 permissions. I'm missing something and can't find what on my own...

Thanks! J.

like image 718
Jem Avatar asked May 13 '26 02:05

Jem


2 Answers

Doesn't answer the question of why the form doesn't provide with a file/url/... but it solves the whole upload issue:

function portal_upload_form_submit($form, &$form_state) {

    $file = $form_state['values']['file'];

    $validators = array();
    $file = file_save_upload('file', $validators, 'public://');
like image 166
Jem Avatar answered May 15 '26 14:05

Jem


Here are a few other things to consider here:

  1. file_save_upload() only will validate a default list of content types: jpg jpeg gif png txt doc xls pdf ppt pps odt ods odp

  2. Be sure to name your first item in an associative array format i.e. '#name' => 'files[img_1]',

file_save_upload() documentation, see the first comment for information on my second point.

like image 20
kevinaskevin Avatar answered May 15 '26 16:05

kevinaskevin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!