Score:0

How can I overwrite existing file and keep same filename when uploading new

bm flag

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.

cn flag
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
bm flag
'field_document' is file field name is this correct?
Score:1
ru flag

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.

bm flag
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?
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.