Last updated August 25, 2012. Created by splondike on December 15, 2008.
Edited by drupalshrek, eltermann, jbergfel. Log in to edit this page.
If your form has a field for uploading a file, in addition to defining a field of type file in your form, you must also set the form's encoding type to multipart/form-data. Use file_save_upload to get an object containing the filename, size, mime type and so on.
If appropriate, use file_copy to move the file to where you want to store it. The original (temporary) file will be automatically removed by drupal at a later date. The following code demonstrates an example of saving an uploaded file for later:
<?php
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."));
}
}
?>
Comments
Wanting extended functionality?
The FAPI is not the only way to upload files. There is the core Upload module, many different CCK fields, and more. For a large listing, see
Image uploading - http://groups.drupal.org/node/21573 & http://drupal.org/node/316884
File uploading / management - http://groups.drupal.org/node/20291
This basic FAPI file field does have it's limitations, for a complete solution out of the box, check out the Upload element module.
Alan Davison
Back roads somewhere in South America
Uploaded files should be
Uploaded files should be stored in a directory under the drupal files directory, and not in a module or theme folder, for security reasons.
Will this work for Drupal 7?
Does anyone know if this code will work in Drupal 7 before I try and blow up my site? Thanks