Search code examples
symfonysymfony4

Download file does not exist


I build a csv export using the admin folder. The file is well uploaded into my public folder. But when I try to download it using the return, I have an error:

The file "/public/exportCSV.csv" does not exist

I can't understand why, I hope you have an idea. Thanks. I'm under Symfony 4.

    $admins = $userRepository->findByRole(User::ROLE_ADMIN);
    $filename='exportCSV';
    $extension='csv';


    $request = Request::createFromGlobals();
    if($request->query->get('exportCSV')!= null){

        $output = fopen($filename.'.'.$extension, 'w');
        fputcsv($output, array("Id","Nom","Prénom","Activé","Dernière connexion","Date d'inscription","Url avatar","Email","Username"));
        foreach ($admins as $admin){
            $id=$admin->getId();
            $lastname=$admin->getLastName();
            $firstname=$admin->getFirstName();
            $activeState=$admin->getActiveState();
            if($activeState){
                $active='Oui';
            }else{
                $active='Non';
            }
            $lastConnectedAt=$admin->getLastConnected();
            if($lastConnectedAt==null){
                $lastConnected=" ";
            }else{
                $lastConnected=$lastConnectedAt->format('Y-m-d H:i:s');
            }
            $createdAt=$admin->getCreatedAt();
            if($createdAt==null){
                $created=" ";
            }else{
                $created=$createdAt->format('Y-m-d H:i:s');
            }
            $urlAvatar=$admin->getUrlAvatar();
            $mail=$admin->getEmail();
            $username=$admin->getUsername();

            $csvLine= array($id,$lastname,$firstname,$active,$lastConnected,$created,$urlAvatar,$mail,$username);
            fputcsv($output,$csvLine);
        }
        return $this->file('/public/'.$filename.'.'.$extension);

    }

Solution

  • You must use the correct path to webserver "public" dir. Check https://stackoverflow.com/a/48585423/3497902

    In your example, you can do same like ...

     $publicDir = $this->getParameter('kernel.project_dir') . '/public/'; # Your controller must extend AbstractController
     $output = fopen($publicDir . $filename.'.'.$extension, 'w');