symfony - download files

10,241

Solution 1

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.

Solution 2

In the controller you can use $this->file(...)

The file needs full filesystem path with file to download

return $this->file('/home/website/upload/'.$someFile)

Also it is possible to define another name when downloading:

return $this->file('/home/website/upload/'.$someFile, 'MyFile.pdf');
Share:
10,241

Related videos on Youtube

betty39johnson
Author by

betty39johnson

Updated on June 04, 2022

Comments

  • betty39johnson
    betty39johnson almost 2 years

    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.