symfony - download files

2019-03-05 13:21发布

问题:

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.

回答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.