Support for Drupal 7 is ending on 5 January 2025—it’s time to migrate to Drupal 10! Learn about the many benefits of Drupal 10 and find migration tools in our resource center.
By manoj_j on
Hi,
How we can add the file upload field in Drupal 7 custom form.Once uploaded and submitted, the file is to be saved in /sites/all/default/file.
Thanks
Comments
Can I recommend looking at
Can I recommend looking at the examples module. If you look at the last tutorial on forms, it shows how to upload a file, validate, and save.
form_example_tutorial_10
Hi I tried the code in
Hi I tried the code in form_example_tutorial_10
the file was uploaded in the "files" folder inside default.But this error is showing up:
Notice: Undefined property: stdClass::$uri in file_save() (line 575 of includes\file.inc).
PDOException: SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '' for key 'uri': INSERT INTO {file_managed} (filesize, status, timestamp) VALUES (:db_insert_placeholder_0, :db_insert_placeholder_1, :db_insert_placeholder_2); Array ( [:db_insert_placeholder_0] => 0 [:db_insert_placeholder_1] => 1 [:db_insert_placeholder_2] => 1334752869 ) in drupal_write_record() (line 6776 of includes\common.inc).
Can you please advice?
Can you show your code?
Can you show your code?
From the error message it seems you are putting the uri into file_save(), but you should be using the file object instead.
Here it is:under hook_menu:
Here it is:
under hook_menu:
$form['file'] = array(
'#type' => 'file',
'#title' => t('Image'),
'#description' => t('Upload a file, allowed extensions: jpg, jpeg, png, gif'),
);
under hook_validation:
$file = file_save_upload('file', array(
'file_validate_is_image' => array(),
'file_validate_extensions' => array('png gif jpg jpeg'),
));
if ($file) {
if ($file = file_move($file, 'public://')) {
$form_state['values']['file'] = $file;
}
else {
form_set_error('file', t('Failed to write the uploaded file the site\'s file folder.'));
}
}
else {
form_set_error('file', t('No file was uploaded.'));
}
}
under hook_submit:
$file=$form_state['values']['file'];
unset($form_state['values']['file']);
$file->status = FILE_STATUS_PERMANENT;
file_save($file);
drupal_set_message(t('The form has been submitted and the image has been saved, filename: @filename.', array('@filename' => $file->filename)));
Works fine for
Works fine for me.
Thanks It worked !
Thanks It worked !
Multiple Files to Multiple Nodes
This will work.