Search code examples
phpsymfonyheaderdownload

symfony - download files


I am trying download files in controller but in the console I see only really bunch of weird characters instead of download box. I am following this topic Symfony2 - Force file download.

Don't know what is going on... trying to find simplest solution. Here is my code:

 $response = new Response(file_get_contents($file->realPath), 200, array(
            'Content-Type' => $file->mimeType,
            'Content-Length' => filesize($file->realPath),
            'Content-Disposition' => 'attachment; filename=' . $file->name,
        ));
 $response->send();

I've even tried to use the most basic example with header() and readfile(). Does my server need special config or something? Cheers.


Solution

  • Instead of rebuilding that kind of response, you could use Symfony's built-inBinaryFileResponse.

    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    
    $response = new BinaryFileResponse($file);
    

    Please take also a look in the documentation about serving files.