【问题标题】:Removing file after delivering response with Silex/Symfony使用 Silex/Symfony 提供响应后删除文件
【发布时间】:2013-03-06 04:17:26
【问题描述】:

我正在我的 Silex 应用程序中使用 Knp\Snappy\Pdf 生成一个 pdf。文件名是随机的,保存到tmp目录下。

$filename = "/tmp/$random.pdf"
$snappy->generate('/tmp/body.html', $filename, array(), true);

我认为在响应中返回 pdf,

$response = new Response(file_get_contents($filename));
$response->headers->set('Pragma', 'public');
$response->headers->set('Content-Type', 'application/pdf');

return $response;

PDF 正确显示在网络浏览器中。请求完成后,具有随机文件名的文件仍然存在。在返回响应之前,我无法取消链接文件。我尝试使用 register_shutdown_function 注册关闭功能并从那里取消链接文件。但是,这似乎不起作用。有什么想法吗?

【问题讨论】:

  • 你应该对文件使用BinaryFileResponse,它会为你处理标题。

标签: php symfony silex


【解决方案1】:

即使这是旧的,想知道是否有人像我一样最近在谷歌上搜索它。这是我找到的解决方案。

在 Silex 中从 sendFile 返回的 BinaryFileResponse 上有一个 deleteFileAfterSend() 方法。 所以在你的控制器中你可以这样做:

    return $app ->sendFile($filepath)
                ->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $fileName)
                ->deleteFileAfterSend(true);

【讨论】:

    【解决方案2】:

    您可以为此使用finish 中间件:

    完成应用程序中间件允许您在响应发送到客户端后执行任务(例如发送电子邮件或日志记录)

    这就是它的样子:

    $app->finish(function (Request $request, Response $response) use ($app) {
        if (isset($app["file_to_remove"])) {
            unlink($app["file_to_remove"];
        }
    });
    
    //in your controller
    $app["file_to_remove"] = $filename;
    

    【讨论】:

      【解决方案3】:

      Maerlyn 是对的,但在这种情况下,您也可以在返回响应之前取消链接文件,因为文件的内容已经在 $response 中。

      【讨论】:

        猜你喜欢
        • 2017-04-12
        • 2011-10-05
        • 1970-01-01
        • 2016-08-21
        • 2020-01-21
        相关资源
        最近更新 更多