How can I get the uploaded files from the request?

Viewed 728

Why I get always NULL on dump() when I try to get the uploaded files from the request?

I tried to link the dropzone to a Symfony form but I failed (impossible to do 2 forms inside each other)

So I make a new controller test (i make it simple as much as I can)

How can I retrieve the uploaded images using dropzone in the controller?

Controller code:

<?php

namespace App\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;

class TestController extends AbstractController
{
    /**
     * @Route("/test", name="test")
     */
    public function index(Request $request)
    {
        dump($request->files->get('file'));

        return $this->render('test/index.html.twig');
    }
}

HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.css" integrity="sha256-e47xOkXs1JXFbjjpoRr1/LhVcqSzRmGmPqsrUQeVs+g=" crossorigin="anonymous" />
    <div class="row">
        <div class="col-sm-4">
            <form action="{{ path('test')}}" method="POST" enctype="multipart/form-data" class="dropzone">
            <div class="fallback">
                  <input type="file" name="file" />
            </div>
            </form>

        </div>
    </div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.5.1/min/dropzone.min.js" integrity="sha256-cs4thShDfjkqFGk5s2Lxj35sgSRr4MRcyccmi0WKqCM=" crossorigin="anonymous"></script>

</body>
</html>
1 Answers

I think you are trying to send this to the server using the fetch API.

If you wish to use Symfony's Request $request->file->get('file'), you need to wrap the body of the request inside the FormData() object in javascript, as so:

function send() {

   const form = document.querySelector(`form`),
     body = new FormData(form);

   fetch(form.action, { // if you need the response, you can assign fetch to a variable
    method: `POST`,
    body
   });

}
Related