Description
// This can be any valid uri, like 'public://a_folder'.
$fileUri = $reportFilesDirectory . '/' . $filename;
// Use the service machine name 'file.repository'.
$file = $this->fileRepo->writeData($attachment['filecontent'], $fileUri, FileSystemInterface::EXISTS_RENAME);
// Temporary by default, but you can add this to be more clear.
$file->setTemporary();
// Must also save the file, as writeData above only creates it on the file system but not in Drupal.
$file->save();
// Associate by target_id in a file field if you wish. This will automatically add usage to the file.
$entity_object_here->field_name_here[]['target_id'] = $file->id();
Alternatively to the last line above, you can use the 'file.usage' service to add usage to the file. ONLY do this if you're not attaching it to a field.