Paweł Buczkowski
Paweł Buczkowski

Reputation: 49

Problem with uploading file in symfony 5.3

I try to prepare very simple upload controller in Symfony v5.3. I followed official tutorial, but probably I am missing something, and I can't find what it is.

My Type class:

namespace App\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Validator\Constraints\File;

class ImportXType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('upload_file', FileType::class, [
                'required' => true,
                'constraints' => [
                    new File([
                        'mimeTypes' => [
                            'text/csv',
                        ],
                        'mimeTypesMessage' => "This document isn't valid.",
                    ])
                ],
            ]);
    }
}

My Controller:

<?php

namespace App\Controller;

use App\Form\ImportXType;
use Psr\Log\LoggerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;

/**
 * Class ImportController
 * @package App\Controller
 * @Route("/api/v1/import", name="import_api")
 */
class ImportController extends AbstractController
{
    private $logger;

    /**
     * ImportController constructor.
     */
    public function __construct(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }

    /**
     * @Route("/x", name="import_x", methods={"POST"})
     */
    public function importX(Request $request): Response
    {
        $form = $this->createForm(ImportXType::class, null, array('csrf_protection' => false));
        $form->handleRequest($request);

        if ($form->isSubmitted()) {
            if ($form->isValid()) {
                $fileData = $form->getData()['upload_file'];
                if ($fileData) {
                    $this->logger->info(file_get_contents($fileData->getPathname()));
                } else {
                    return new Response("filedata is null", 400);
                }
            } else {
                return new Response("not valid", 400);
            }
        } else {
            return new Response("not submitted", 400);
        }
        return new Response("OK", 200);
    }
}

When I run curl:

curl -i -X POST -H "Content-Type: multipart/form-data" -F "[email protected]" https://localhost:8000/api/v1/import/x

I get not submitted response error.

I found out that changing:

$form->handleRequest($request);

to

$form->submit(array_merge([], $request->request->all()));

can help, but after this change I get another error: filedata is null

Please help me to find out what I am missing...

Upvotes: 2

Views: 2040

Answers (3)

Steph TwX
Steph TwX

Reputation: 87

try this:

if ($form->isValid()) {
   $fileData = $form['upload_file']->getData();
   ...

like in this example

Upvotes: 1

Muh Fadjar Rhomadoni
Muh Fadjar Rhomadoni

Reputation: 371

Based on official doc

you need to use $request->get('upload_file')->getData() to get UploadedFile object

Upvotes: 0

Paweł Buczkowski
Paweł Buczkowski

Reputation: 49

Finally

$request->files->get("upload_file")

did what I wanted. But I still cannot understand while symfony form is not handling it properly... :(

Upvotes: 1

Related Questions