phpsymfonysymfony-3.4symfony-http-foundation

Symfony HttpFoundation get single file returns null?


I use symfony HttpFoundation for upload files, the FileBag works if I call all(), but if I use get('document_name') it return null.

use Symfony\Component\HttpFoundation\Request;


    public function saveFileAction(Request $request) {
        dump($request->files->all());
        dump($request->files->get('document'));
    }

For all() I get following response:

FileController.php on line 175:
array:1 [▼
  "form" => array:1 [▼
    "document" => UploadedFile {#14 ▶}
  ]
]

What I do wrong here? Does somebody know why I can't get the single file with get() method? I found in symfony documentation I found that $request->files->get('document') should work...


Solution

  • $request->files->get("document") is correct if the POST field really is named as this. (Check with your browser's network inspector to be sure.) I suspect the field is named differently, or this would work.

    If it's coming from a file input within a managed form class you should instead be using $form->get("document")->getData(); to retrieve your UploadedFile instance. Guessing from the form[document] name you mentioned in a comment, and the output of $request->files->all(), this is highly likely the case.

    If you really do need to read it raw from the request attributes you'd need to use $request->files->get("form[document]"); as Symfony would not have expanded the array-like form input name when reading it raw from request attributes. This is the same if you had a text box input, you'd have to read it with $request->request->get("form[firstName]");, but as I mentioned you should make proper use of the managed form class way $form->get("document")->getData(); if this really is a managed form. (Symfony has already thought of this for you in advance, including cascading the input answer to validation rules and data models.)

    Otherwise I'd be interested to know how you're uploading this form in the first place. (Is it AJAX?)