Macbernie
Macbernie

Reputation: 1323

Serve file as a download with Silex

My controller is basic

$app->get('/files/{type}', function ($type) use ($app) {

    $path = __DIR__ . "/../files/$type";

    if (!file_exists($path)) {
        $app->abort(404, "Ce fichier n'existe pas.");
    }

    return $app
        ->sendFile($path)
    ;
})->bind('getfile');

According to this doc it works. When I call a correct URL, the file is open on the current window.

But I don't want to open the file in the browser, I want to open the dialog box to just save the file.

How can I do that ?

Upvotes: 3

Views: 2052

Answers (1)

yivi
yivi

Reputation: 47380

You need to set the "content-disposition" header to attachment.

E.g.:

return $app
    ->sendFile($path)
    ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,
basename($path));

Don't forget to add this at the top of your file:

 use Symfony\Component\HttpFoundation\ResponseHeaderBag;

... so PHP knows what ResponseHeaderBag is, and the autoloader is able to find it.

Linky to docs.

Upvotes: 8

Related Questions