Uploading Files with Drupal 6

| No Comments

Here's a relatively painless example for file uploads in Drupal 6.

This code is in a module file called usertab.module:

#create the form
function usertab_admin($form_state) {
  #prepare the file upload form
  $form = array('#attributes' => array('enctype' => 'multipart/form-data'));

  #file selector element
  $form['csv'] = array(
      '#type' => 'file',
      '#title' => 'Upload users',
      '#description' => t('Pick a csv file to upload')

  #submit button
  $form['submit'] = array('#type' => 'submit', '#value' => 'Upload');
   return $form;

#handle the form submission
function usertab_admin_submit($form, &$form_state) {

  #this leads us to sites/mysite.example.com/files/
  $dir = file_directory_path();
  # unlike form submissions, multipart form submissions are not in 
  # $form_state, but rather in $FILES, which requires more checking
  if(isset($_FILES) && !empty($_FILES) && $_FILES['files']['size']['csv'] != 0)){
    #this structure is kind of wacky
    $name = $_FILES['files']['name']['csv'];
    $size = $_FILES['files']['size']['csv'];
    $type = $_FILES['files']['type']['csv'];

    #this is the actual place where we store the file
    $file = file_save_upload('csv', array() , $dir);
      drupal_set_message("You uploaded $name!");
        drupal_set_message("Something went wrong saving your file.");
  else {
    drupal_set_message("Your file doesn't appear to be here.");
Here are some of the strange things going on here:

First, the structure of the $_FILES array in php is kind of strange. There's a good diagram of it here: http://www.php.net/manual/en/features.file-upload.post-method.php#91479. Notice that it's the second one in the example.

Next, Drupal's (6) file_save_upload() method. The API documentation is here: http://api.drupal.org/api/drupal/includes--file.inc/function/file_save_upload/6, but the parameters can be kind of confusing so here are some details:

  1. $source is the name of the file in the $_FILES array (also the name of the file field on form.
  2. $validators are outside the scope of this example.
  3. $dest is relative to the drupal root directory.
  4. $replace is actually self-explanatory

P.S. At some point, I will figure out how to get some syntax highlighting going here.

Leave a comment

About this Entry

This page contains a single entry by Jeff Kerzner published on January 4, 2011 4:47 PM.

Debian/Shorewall routing issues was the previous entry in this blog.

Capistrano and svn prompts is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.