I've uploaded a file in a custom form and I can retrieve the file instance like this:

  $fid = $form_state->getValue('file')[0];
  $file = File::load($fid);

How can I get the contents of the file?


Returns false. If I visit the link manually, it gets downloaded.

1 Answer 1


You can't get the file from $form_state->getValue(). You have to upload the file first to the file table as temporary file with file_save_upload(). Then you can load the file content locally from $file->getFileUri().

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

    $validators = ['file_validate_extensions' => ['txt']];
    if ($file = file_save_upload('file', $validators, FALSE, 0)) {
      $data = file_get_contents($file->getFileUri());


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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