Saturday, January 22, 2011

Uploading files in Drupal 6

function myform() {
$form = array();
// If this #attribute is not present, upload will fail on submit
$form['#attributes']['enctype'] = 'multipart/form-data';
$form['file_upload'] = array(
'#title' => t('Upload file'),
'#type' => 'file',
);
$form['submit_upload'] = array(
'#type' => 'submit',
'#value' => 'Submit'
);
return $form;
}

function myform_submit($form, &$form_state) {
$validators = array();
$dest = 'upload_directory';
$file = file_save_upload('file_upload', $validators, $dest);
//$file will be 0 if the upload doesn't exist, or the $dest directory
//isn't writable
if ($file != 0) {
$dest_path = 'upload_directory/file';
$result = file_copy($file, $dest_path, FILE_EXISTS_RENAME);
if ($result == 1) {
//Success, $file object will contain a different (renamed)
//filename and filepath if the destination existed
}
else {
//Failure
}
}
else {
form_set_error('myform', t("Failed to save the file."));
}
}

No comments:

Post a Comment