使用Silex下载文件作为下载

Mac*_*nie 3 php symfony silex

我的控制器是基本的

$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');
Run Code Online (Sandbox Code Playgroud)

根据这个文档它是有效的.当我调用正确的URL时,该文件在当前窗口中打开.

但是我不想在浏览器中打开文件,我想打开对话框来保存文件.

我怎样才能做到这一点 ?

yiv*_*ivi 7

您需要将"content-disposition"标头设置为attachment.

例如:

return $app
    ->sendFile($path)
    ->setContentDisposition(ResponseHeaderBag::DISPOSITION_ATTACHMENT,
basename($path));
Run Code Online (Sandbox Code Playgroud)

不要忘记在文件顶部添加:

 use Symfony\Component\HttpFoundation\ResponseHeaderBag;
Run Code Online (Sandbox Code Playgroud)

...所以PHP知道什么ResponseHeaderBag是,自动加载器能够找到它.

Linky to docs.