I've got this form:

 $form['import_json'] = [
      '#type' => 'file',
      '#description' => $this->t('Allowed extensions: json'),
      '#title' => $this->t('Import your JSON\'s file.'),

    $form['submit'] = [
      '#type' => 'submit',
      '#value' => $this->t('Import'),

I have to use '#type' => 'file' because AFAIK managed_file doesn't allow json file and file is the only type left.

I need to be able to get the uploaded file when the user submit the form to be able to convert the JSON's data to create nodes of a certain type.

My function is already created and it looks like this:

protected function createActualite(string $json)

    $jsonstring = json_decode($json, TRUE);

    foreach ($jsonstring as $field) {
      $node = Node::create([
        'type' => 'import_content', // Machine name de notre content type 'actualité'
        'title' => $field['titre'],
        'body' => $field['body'],

The problem is that I can't find a way to properly get the uploaded file, I tried the same way that we do with managed_file

$file = File::load($field['import_json']);

but it doesn't work, also this (which is 10yo) doesn't do the trick either gist

If someone can lead me to arrive to save this file or to any doc, I would greatly appreciate.

  • You might want to walk through the csvimport sample module which I co-maintain. It shows you how to handle the file upload and shows you how to implements a batch process to prevent timeouts on node creation when trying to create many 1000 nodes at once.
    – leymannx
    Jun 8, 2020 at 20:14

1 Answer 1


Ok I made it works, first I get the file's path using the solution given here

and then once I got the path, I'm reading the file using

$file = file_get_contents($file_path);

then calling my function createActualite($file); and it creates all the nodes up to the content of the JSON as expected.

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.