With managed file, dynamically set fileName and #upload_location In a form I want to bulk upload jpgs renaming them using exif date information and dynamically setting the #upload_location according to the value of a textfield in the same form.
I have no problem with accessing the exif date information. What I don't know how to do, is dynamically set the file name and file path (actual location on the server) programmatically.
This is my form upload element:
$form['images'] = array(
  '#type' =&gt; 'managed_file',
  '#multiple' =&gt; TRUE,
  '#upload_validators' =&gt; array(
    'file_validate_extensions' =&gt; array('jpg'),
  ),
  '#upload_location' =&gt; 'public://photos',
  '#required' =&gt; TRUE,
);

$form['file'] = [
  '#type' =&gt; 'fieldset',
  '#title' =&gt; $this-&gt;t('File'),
];

$form['file']['name'] = [
  '#type' =&gt; 'textfield',
  '#title' =&gt; $this-&gt;t('File name'),
  '#description' =&gt; $this-&gt;t(
    'Is suffixed by the exif creation date-time plus fid cleaned for urls. If not set the original file name will be used.'
  ),
];

$form['file']['path'] = [
  '#type' =&gt; 'textfield',
  '#title' =&gt; $this-&gt;t('File path'),
  '#placeholder' =&gt; 'path/to/directory',
  '#description' =&gt; $this-&gt;t(
    'Path to the files sub-directory, default is &quot;photos&quot;. Sub-dirs will be create if necessary.'
  ),
];

I've tried using something like this in both validateForm() and submitForm().
$images = $form_state-&gt;getValue('images');
$file = File::load( $images[0] );
$file-&gt;setFileName(&quot;xxx2&quot;);
$file-&gt;setFileUri(&quot;public://photos/test/xxx2.jpg&quot;);

Although this changes the values of the $file object, it doesn't change the real path. The jpg files are also still in /sites/default/files/photos/ with their original name plus a unique counter.
So to repeat my question:
How can I set the upload_location and the fileName of a managedFile dynamically and programmatically in a submitForm() or validateForm() function using methods that are not marked deprecated in drupal 8.
Thanks @Clive. I just read your comment, but in the mean time I found the answer myself. This is the essentials of my code in my submitForm() method. It still seems a bit hacky to me but it works.
$images = $form_state-&gt;getValue('images');
$file = File::load( $images[0] );

$file-&gt;setPermanent();
$file-&gt;save();

$new_filename = &quot;photos/test/test-02.jpg&quot;;
$stream_wrapper = \Drupal::service('file_system')-&gt;uriScheme($file-&gt;getFileUri());
$new_filename_uri = &quot;{$stream_wrapper}://{$new_filename}&quot;;

file_move($file, $new_filename_uri); // &lt;===== The essential line!

$file = File::load( $images[0] );
dpm($file-&gt;getFilename()); // returns test-02.jpg
dpm($file-&gt;getFileUri());  // returns public://photos/test/test-02.jpg