How to change the name of uploaded file in my custom Entity? I have a custom Content Entity created with

public static function baseFieldDefinitions(EntityTypeInterface $entity_type)


In the definition, there is a 'file' field:

$fields['file1'] = BaseFieldDefinition::create('file')
-&gt;setLabel(t('Fichier source'))
-&gt;setDescription(t('Source document (can be edited)'))
-&gt;setSettings([
'target_type' =&gt; 'file',
'file_extensions' =&gt; 'doc docx odt pages',
'file_directory' =&gt; 'contrats',
])
-&gt;setDefaultValue('')
-&gt;setDisplayOptions('view', [
'label' =&gt; 'above',
'type' =&gt; 'string',
'weight' =&gt; 7,
])
-&gt;setDisplayOptions('form', [
'type' =&gt; 'string_textfield',
'weight' =&gt; 7,
])
-&gt;setDisplayConfigurable('form', TRUE)
-&gt;setDisplayConfigurable('view', TRUE)
-&gt;setReadOnly(TRUE);


And it works fine!
My question is: how can I change the name of an uploaded file?
I guess I should use hook_entity_presave.
But how to retrieve file information in hook_entity_presave?
Using the comments already given (thanks), I added this:

function tempo_entity_presave(EntityInterface $entity)
{
if ($entity-&gt;getEntityType()-&gt;id() == "amap_contrats") {
$sName  = 'Contrat-'.$entity-&gt;typecontrat-&gt;target_id.'-'.str_replace("-", "", $entity-&gt;datedebutcontrat-&gt;value);
$fid1[0]['target_id'];
$fid1 = $entity-&gt;get('file1')-&gt;target_id;
$file = file_load($fid1);
$sName1 = $sName.'.'.pathinfo($file-&gt;filename-&gt;value, PATHINFO_EXTENSION);
$result = file_move($file1, $sName1, FILE_EXISTS_REPLACE);
$sName2 = $sName . '.pdf';
$result =file_move($file2, $sName2, FILE_EXISTS_REPLACE);
}
}


And now, I get this error:

Argument 1 passed to file_move() must implement interface Drupal\file\FileInterface, null given, called in /Applications/MAMP/htdocs/JdP8M3/modules/custom/tempo/tempo.module on line 48 in /Applications/MAMP/htdocs/JdP8M3/core/modules/file/file.module on line 216 #0 /Applications/MAMP/htdocs/JdP8M3/modules/custom/tempo/tempo.module(48): file_move(NULL, 'Contrat-5-20170...', 1)


Any idea?

OK, I got it! My mistake:
I load '$file' and I try to file_move '$file1' :-(
Please refer the below articles it will be helpful for you..

How do I change the uploaded file name after the node has been saved?

Changing file name on upload