Processing File Contents in Form Uploads

Suppose you want a form that allows the user to select a file. We want to upload that file and then process its contents.

First define the file in the form definition function

// File
$form['file'] = array(span>
  '#type' => 'file',
  '#name' => 'files[import]',
  '#title' => t('Choose a file'),
  '#description' => t('Input file must be TAB delimited....'),
);

The important part is that the #name must be in array form.

Then in the submit function, we can set up a validator. For all files, it will be very simple,

$validators = array(
  'file_validate_extensions' => array(),
);

To restrict to just CSV files

$validators = array(
  'file_validate_extensions' => array('csv'), // Validate extensions.
  FILE_EXISTS_REPLACE,
);

You can send an empty array if you want for default options. Or set your own options, for example

$validators = array(
    'file_validate_is_image' => array(),
    'file_validate_image_resolution' => array(variable_get('btn_dimensions', '124x124')),
    'file_validate_size' => array(variable_get('btn_file_size', '5') * 1024),
);

We can now convert that to a file record format.

$file = file_save_upload('import', $validators);

Which is of the format

stdClass Object (
    [uid] => 1
    [status] => 0
    [filename] => brand.csv
    [uri] => temporary://brand.csv
    [filemime] => text/csv
    [filesize] => 488
    [source] => import
    [destination] => temporary://brand.csv
    [timestamp] => 1377785481
    [type] => default
    [fid] => 7005
)

We can determine the local path of the file

$path = drupal_realpath($file -> uri);

And then get the contents normally.

$data = file_get_contents($path);

Leave a comment

Your email address will not be published. Required fields are marked *