下载文件不存在

时间:2019-01-22 16:42:30

标签: symfony symfony4

我使用admin文件夹构建了一个csv导出。该文件已很好地上传到我的公共文件夹中。 但是,当我尝试使用return下载它时,出现错误:

  

文件“ /public/exportCSV.csv”不存在

我不明白为什么,希望您有个主意。谢谢。我在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);

    }

1 个答案:

答案 0 :(得分:1)

您必须使用指向Web服务器“公共”目录的正确路径。选中https://stackoverflow.com/a/48585423/3497902

在您的示例中,您可以像...一样做

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