I have content type 'Document' and added the 'Upload document' field with type 'File' I want to replace file and update the node. I'm using below code

function custom_file_upload_form_alter(&$form, $form_state, $form_id) {
  if($form_id == "test_node_form") {
    $form['#submit'][] = 'custom_fileupload_submit';

function custom_fileupload_submit(&$form, &$form_state) {
 $file = file_save_upload('field_document', array(
    'file_validate_extensions' => array('pdf'), // Validate extensions.
    'public://', FILE_EXISTS_REPLACE
  if ($file) {
    // Move the file, into the Drupal file system
    if ($file = file_move($file, 'public://', FILE_EXISTS_REPLACE)) {
      // Save the file for use in the submit handler.
      $form_state['storage']['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.'));

Here file_save_upload() not working. I have debug the $file variable but it's print nothing.

  • 2
    Look at your call to file_save_upload more carefully. It's likely you didn't mean to include the destination and constant as part of the validation array
    – Clive
    Feb 10 at 13:15
  • 'field_document' is file field name is this correct?
    – user66981
    Feb 10 at 14:16

1 Answer 1


You can just use the Upload File Replace module to solve this use case instead of custom code:

This is a small utility module that automatically stops Drupal from renaming new files upload via filefield CCK. When 2 files with the same name exist, the older files will be renamed.

  • Yes I have tried this module it's not working with another functionality related to file upload. Is there any other way to do by custom module?
    – user66981
    Feb 14 at 11:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.