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);
if($file){
drupal_set_message("You uploaded $name!");
}
else{
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:
- $source is the name of the file in the $_FILES array (also the name of the file field on form.
- $validators are outside the scope of this example.
- $dest is relative to the drupal root directory.
- $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