I wish to rename the files and change the directory on upload.

I have an image field which allow multiple upload by using Plupload integration module.

By using the hook_file_validate, i able to change the filename, uri, destination in the $file object and leave the rest as it is, it seems ok. Images are showing in the node, data in database is fine.

My question is this a proper way? Any hidden problems i might face in future?

Please let me know if you have any suggestion.

Thanks!

Comments

BlackyWhoElse’s picture

<?php
$form['image_fid'] = array(
  '#title' => t('Image'),
  '#type' => 'managed_file',
  '#upload_location' => 'public://',
  '#upload_validators'=>  array('file_validate_name' => array()),
);

function file_validate_name(stdClass $file) {
  $errors = array();

  //generate file name 
  $new_filename = convert_filename_to_filename_date($file->filename);


  $file->filename = $new_filename;

  //changing file location 
  $destination_dir = "public://file_location/";

  //check if file exists. if exists rename it append incremental number  until the filename is unique

  $file->destination = file_destination($destination_dir.$file->filename, FILE_EXISTS_RENAME);

  // If file_destination() returns FALSE then $replace == FILE_EXISTS_ERROR and
  // there's an existing file so we need to bail.
  if ($file->destination === FALSE) {
    $errors[] = t('The file %source could not be uploaded because a file by that name already exists in the destination %directory.',
    array('%source' => $file->source, '%directory' => $destination_dir));
  }

  return $errors;
}
?>
drupalz001’s picture

this seems to be a better way, thanks a lot!

BlackyWhoElse’s picture

Your welcome