How do I save a file with managed_file in a theme? I'm developing a theme that it requires to have a header image on the front page, so I have this.

casper.theme

function casper_form_system_theme_settings_alter(&amp;$form, &amp;$form_state) {

$form['theme_extra']['front_page_background_image'] = array(
    '#type' =&gt; 'managed_file',
    '#title' =&gt; 'Front Page Background Image',
    '#description' =&gt; 'Add background image for the front page',
    '#required' =&gt; FALSE,
    '#weight' =&gt; -4,
    '#upload_location' =&gt; file_default_scheme() . '://theme/backgrounds/',
    '#default_value' =&gt; theme_get_setting('front_page_background_image' , 'casper'),
    '#upload_validators' =&gt; array(
        'file_validate_extensions' =&gt; array('gif png jpg jpeg'),
    ),
 );
}


However, after it, while the file been missing and after some reading, I find out that is because managed_file does not save your image permanent. 

There are similar questions:


Is there a way to add managed_file field to theme-settings.php? is specified to Drupal 7.
Drupal 8 Theme Header Background Image Upload is using "file" type instead of managed_file. I already tried something similar to what the Mayo theme is doing, but I was not able to successfully figure it out.


How can I save my image permanently?
The way it was done in Drupal 7 was that you wrote a function for hook_form_submit where you would 

// Get the File ID (fid).
$fid = $form_status['values']['managed_file_field'];

// Load the file.
$file = file_load($fid);

// Set the status to permanent.
$file-&gt;status = FILE_STATUS_PERMANENT;

// Finally save the file.
$file-&gt;save();


You can read more about this with a great Drupal 7 example here.
I'm sure there's something similar on Drupal 8. You'll just need to register a submit handler for the form. Take a look at the docs for managed_file if you want to go that route. here for it.