How do I save a uploaded file with status equal to 1 in the file_managed table, in Drupal 8?

Whenever I upload a file, it is stored in the file_managed table with status value 0.
I have used File::load( $form_state->getValue('image')) to load the file. What do I need to do next?

In Drupal 7, I would use $file->status = FILE_STATUS_PERMANENT. What is the equivalent code for Drupal 8?

class AddBannerForm extends FormBase {

public function getFormId()
  return 'add_banner_form';

public function buildForm(array $form, FormStateInterface $form_state)

  $form['image'] = array(
    '#type'          => 'managed_file',
    '#title'         => t('Choose Image File'),
    '#upload_location' => 'public://images/',
    '#default_value' => '',
    '#description'   => t('Specify an image(s) to display.'),
    '#states'        => array(
      'visible'      => array(
        ':input[name="image_type"]' => array('value' => t('Upload New Image(s)')),

  $form['submit'] = array(
    '#type' => 'submit',
    '#value' => t('Save image'),

  return $form;

public function validateForm(array &$form, FormStateInterface $form_state)
    File::load( $form_state->getValue('image') );

public function submitForm(array &$form, FormStateInterface $form_state)


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 */

/* Save the file in database */
  • Now can you do this in a schema.yml file ? – Guillaume Bois Nov 7 '16 at 13:44
  • 5
    Nice @Jasodeep !! However this wasn't enough for me to work on. After setting setPermanent() & save(). I had to do an extra step $file_usage = \Drupal::service('file.usage'); $file_usage->add($file, 'mymodule', 'mymodule', \Drupal::currentUser()->id()); :) hope this helps!! – JayKandari Jun 13 '17 at 14:19

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)) {
    // Save the file in the database.
    $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'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.