As I needed to know some data about the node which the file is added to, none of hook_file_update, hook_file_presave or hooks like that was proper for my needs, while I was searching I found a drupal 7 solution, so I changed the code to get it to work.
Here is the module I wrote, this module works on any file and image field :
<?php
/**
*@file
* this module alters node forms and adds a submit handler which inside that it renames the uploaded files
*/
use Drupal\Core\Form\FormStateInterface;
use Drupal\file\Entity;
use Drupal\Core\Entity\ContentEntityForm;
function file_name_converter_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$bundle = FALSE;
$form_object = $form_state->getFormObject();
if ($form_object instanceof ContentEntityForm) {
$bundle = $form_object->getEntity()->bundle();
$form_state->set('#bundle_value', $bundle);
foreach (array_keys($form['actions']) as $action) {
if ($action != 'preview' && isset($form['actions'][$action]['#type']) && $form['actions'][$action]['#type'] === 'submit') {
$form['actions'][$action]['#submit'][] = 'file_name_converter_node_form_submit';
}
}
}
}
function file_name_converter_node_form_submit(&$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
$bundle = $form_state->get('#bundle_value');
$bundle_fields = \Drupal::entityManager()->getFieldDefinitions('node', $bundle);
foreach ($bundle_fields as $field_name => $field_definition) {
if (!empty($field_definition->getTargetBundle())) {
$field_type = $field_definition->getType();
if($field_type == 'image' || $field_type == 'file') {
if(!empty($values[$field_name])) {
foreach ($values[$field_name][0]['fids'] as $delta => $fid) {
$file = file_load($fid);
$uri = $file->getFileUri();
$fname = $file->getFilename();
$exp = explode('.', $fname);
$extnsn = $exp[count($exp)-1];
$new_name = 'MySite-' . $field_type . '-' . $bundle . '-' . $values['nid'] . '.' . $extnsn;
$new_uri = str_replace($fname, $new_name, $uri);
// And finally rename the file.
file_move($file, $new_uri);
}
}
}
}
}
}