3

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.

Community
  • 1
  • 1
betty39johnson
  • 151
  • 1
  • 2
  • 12

2 Answers2

7

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.

Michael Hirschler
  • 2,345
  • 16
  • 28
3

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');
Kaxa
  • 515
  • 1
  • 6
  • 11