php - 在Symfony中返回内存中的文件

标签 php symfony

我正在尝试在Symfony Controller 中返回BinaryFileResponse响应,但它要求提供路径或File对象。事实是,我正在通过SOAP服务获取文件,它创建了一个像这样的对象:filename + base64 encoded content + mime + extra stuff

我真的不想将其保存到磁盘然后创建响应...

也许我现在视而不见,但是有什么方法可以发送它而不在磁盘上创建文件?

这是 Action :

public function downloadAction($hash){
   $document = $this->get('soap_services.document_service')->findDocument($hash);

   return $this->file($SymfonyFileObjectOrPath, $fileName);
}
$document对象提供以下相关方法:getMime,getName,getContent。

这就是我想用来在不创建File对象(以及它所隐含的物理文件)的情况下进行响应的原因。

最佳答案

您好,也许您应该考虑做出回应并“手动”强制下载。

// Generate response
$response = new Response();
$filename = 'yourFileName.txt';

// Set headers
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', $yourMimeType );
$response->headers->set('Content-Disposition', 'attachment; filename="' . $filename . '";');
$response->headers->set('Content-length',  strlen($yourContentString));

// Send headers before outputting anything
$response->sendHeaders();

$response->setContent( $yourContentString );

return $response;

也许像这样的东西可以解决问题。
您可以尝试一下,也许可以稍微改变一下吗?

关于php - 在Symfony中返回内存中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41804695/

相关文章:

php - 使用SQL同时更新两个字段的语法

php - 在数组中跳过 mysql 数据库中的值

php - 使用 PHP 在每个月的 HTML 表中显示日期

php - 在函数中模拟 Propel 查询 (Symfony2)

session - symfony2 session 自动启动

php - 正则表达式 PHP。减少步骤: limited by fixed width Lookbehind

php - 根据 WooCommerce 购物车总数和月份范围添加或删除免费产品

symfony - 如何在 Symfony 中的表单中添加未绑定(bind)的字段,否则绑定(bind)到实体?

php - 使用 Twig 模板时,有没有办法从数组中获取平均值?

php - 弄清楚如何配置特定的 services.yml 值 - Symfony2