
Drupal
Posted September 8th, 2008 by shunting
Uploading a file in D6 is a bit trickier than maybe it should be.
$form = array();
// If this #attribute is not present, upload will fail on submit
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['logotool_captions_upload'] = array(
'#title' => t('Upload captions'),
'#type' => 'file',
'#description' => t("...");
$form['submit_upload'] = array('#type' => 'submit', '#value' => 'Upload caption list');
return $form;
}
function logotool_captions_submit($form, &$form_state) {
global $base_path;
switch ($form_state['clicked_button']['#post']['op']) {
case 'Upload caption list':
$dest = file_directory_path() . '/' . LOGOTOOL_CWD; // not accepted!
$validators = array();
$file = file_save_upload('logotool_captions_upload', $validators, $dest);
/* Let's just copy what that user.module does, which is to copy
* the file out of the tmp directory to the real destination. From
* that module:
* The image was saved using file_save_upload() and was
* added to the files table as a temporary file. We'll make a
* copy and let the garbage collector delete the original upload.
*/
// dest_filepath is path to a file, not to a directory.
// Unlike file_save_upload.
if ($file != 0) {
$dest_filepath = file_directory_path() . '/' . variable_get('logotool_folder','logos') . '/' . LOGOTOOL_CAPTIONS_FILENAME;
$result = file_copy($file->filepath, $dest_filepath, FILE_EXISTS_REPLACE);
if ($result == 1) {
drupal_set_message(t("%file uploaded successfully", array('%file' => $file->filename)));
}
else {
// chmod 775; chown for apache (e.g., www, not user).
form_set_error('logotool_captions', t("Failed to upload the logo; the %directory directory doesn't exist or is not writable.", array('%directory' => $dest_filepath)));
}
}
else {
form_set_error('logotool_captions', t("Failed to save the file."));
}
break;
}
}

