How do I programmatically attach a file to a file field in a node?
In your custom form use code like this:

$form['imagefile'] = [
      '#type' =&gt; 'managed_file',
      '#title' =&gt; $this-&gt;t('Imagefile'),
      '#default_value' =&gt; $this-&gt;configuration['imagefile'],
      '#weight' =&gt; '0',
      '#upload_location' =&gt; 'public://images/redaktion/',
    ];


And here's a piece of code how it works low level:

// check if the folder exists
$folder = date('Y-m', time());
$data = file_get_contents($imagefilepath);
if (!is_dir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}")) {
      mkdir("/home/rainer/src/asdent/web/sites/default/files/images/pics/{$folder}");
}
// create the file entity
$photo = file_save_data($data, "public://images/pics/{$folder}/".$filename, FILE_EXISTS_REPLACE);

// later in your entity::create:
'myimage' =&gt; ['target_id' =&gt; $photo-&gt;id()],


The trick is to create the file entity beforehand and then link the custom entity to it.