Drupal - How do I save uploaded file permanently in file_manged table?

Thank you @Clive & @kiamlaluno

/* Fetch the array of the file stored temporarily in database */ 
   $image = $form_state->getValue('image');

/* Load the object of the file by it's fid */ 
   $file = File::load( $image[0] );

/* Set the status flag permanent of the file object */
   $file->setPermanent();

/* Save the file in database */
   $file->save();

Use this code to save the image permanently in the configuration form, if you are using Drupal 8.

public function submitForm(array &$form, FormStateInterface $form_state) {
  parent::submitForm($form, $form_state);
  $image = $form_state->getValue('welcome_image');
  // Load the object of the file by its fid. 
  $file = File::load($image[0]);
  // Set the status flag permanent of the file object.
  if (!empty($file)) {
    $file->setPermanent();
    // Save the file in the database.
    $file->save();
    $file_usage = \Drupal::service('file.usage'); 
    $file_usage->add($file, 'welcome', 'welcome', \Drupal::currentUser()->id());
  }
  $config = $this->config('welcome.settings');
  $config->set('welcome_text', $form_state->getValue('welcome_text'))
    ->set('welcome_image', $form_state->getValue('welcome_image'))
    ->save();
}

Tags:

8