Skip to main content

File uploads in Drupal 6 - Part 1

21st Jan 2009

Steven Jones

Senior Developer

So you've got a nice new version of Drupal 6 and you're building a form, but you want to allow users to upload a file. Of course this is easy with Drupal, and we covered how to do just that, but for Drupal 5, in our previous article: Example code to build an upload form in Drupal. Here we show how file uploads are done in Drupal 6.

Honestly, not much has changed, here's the code to get your file upload element onto your form:

function build_upload_form(){
    $form['#attributes'] = array('enctype' => 'multipart/form-data');
    $form['file_upload'] = array(
        '#type' => 'file',
        '#title' => 'Filename'
    $form['submit'] = array(
        '#type' => 'submit',
        '#value' => 'Upload file'
    return $form;

Nothing has changed since Drupal 5 there, but the changes come in the submit function:

function upload_form_submit($form, &$form_state) {

  //define your limits for the submission here
  $limits = array ( ... ) ;

  $validators = array(
    'file_validate_extensions' => array($limits['extensions']),
    'file_validate_image_resolution' => array($limits['resolution']),
    'file_validate_size' => array(

  // Save new file uploads.
  if ($file = file_save_upload('file_upload', $validators, file_directory_path())) {
    // Do something with $file here.

We have a big change here, we can define an array of file validation functions to pass to file_save_upload and only if the file conforms to those will it be saved.

File validation functions:

These are simply functions that receive the $file object as their first parameter and extra parameters as defined in your invocation of file_save_upload(). Drupal core comes with four:

  1. file_validate_extensions() checks that the file extension in the given list
  2. file_validate_size() checks for maximum file sizes and against a user's quota
  3. file_validate_is_image() checks that the upload is an image
  4. file_validate_image_resolution() checks that images meets maximum and minimum resolutions requirements.

You can always write your own to check extra things, you just need to return an array of error messages if there are any, and an empty array if not. More information can be found in the Drupal handbook.

Next Steps

We're not going to cover what you could do with your uploaded and validated file object, but there is one obvious thing that you might want to do before all that: AJAX uploading.
Drupal's core upload module allows you to upload files to nodes, and provides a nice 'attach' button which starts the upload process in the background leaving users free to fill in the rest of the form, doing this with your own forms turns out to be quite challenging, as we shall see in the next part of this tutorial!