How to upload a file in Drupal 8 using FAPI

This is a simple code snippet to show you how to upload a file and save it into the database without much effort. D8 makes it really easy by having its own file form element type.

First, add your form element into your form method.

  $form['file'] = [
    '#type' => 'managed_file',
    '#title' => t('File'),
    '#upload_location' => 'public://file',
    '#upload_validators' => [
      'file_validate_extensions' => ['csv'],
    ],
    '#default_value' => array(2)
  ];

"2" here is the file id.

Then you handle the saving the file as a permanent file into the file_managed table. So add this to your submit handler.

  use Drupal\file\Entity\File;

  $fid = $form_state->getValue(['file', 0]);
  if (!empty($fid)) {
    $file = File::load($fid);
    $file->setPermanent();
    $file->save();
  }