Symfony2 - 强制下载文件 [英] Symfony2 - Force file download

查看:36
本文介绍了Symfony2 - 强制下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户点击下载链接时,我正在尝试下载文件.

I'm trying to download a file when a user clicks on download link.

在控制器中:

    $response = new Response();
    $response->headers->set('Content-type', 'application/octect-stream');
    $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
    $response->headers->set('Content-Length', filesize($filename));

    return $response;

这是打开保存文件的对话框,但显示文件为 0 字节.并将其更改为:

This is opening the dialog box to save the file, but it says the file is 0 bytes. And changing it to:

        $response = new Response();
        $response->headers->set('Content-type', 'application/octect-stream');
        $response->headers->set('Content-Disposition', sprintf('attachment; filename="%s"', $filename));
        $response->headers->set('Content-Length', filesize($filename));
        $response->headers->set('Content-Transfer-Encoding', 'binary');
        $response->setContent(readfile($filename));

        return $response;

我得到了一堆奇怪的字符,而不是文件下载对话框.

I get a bunch of weird characters instead of the file download dialog box.

最后,将setContent"行切换为:

Finally, switching the "setContent" line to:

    $response->setContent(file_get_contents($filename));

它返回一个 PHP 错误:

It returns a PHP error:

致命错误:允许的内存大小...

Fatal error: Allowed memory size...

有关如何实现这一目标的任何线索?我以前用 PHP 做过(没有 MVC),但我不知道通过 Symfony2 做它会缺少什么......

Any clues on how to achieve this? I've done it before in PHP (wihtout MVC), but I don't know what can be missing to do it through Symfony2...

也许解决方案是在 PHP.INI 中设置 memory_limit,但我想这不是最佳实践...

Maybe the solution is setting the memory_limit in PHP.INI, but I guess it´s not the best practice...

推荐答案

我终于在没有 X-SendFile 的情况下解决了这个问题(这可能是最佳实践).无论如何,对于那些无法让 X-Sendfile apache 模块工作(共享托管)的人,这里有一个解决方案:

I finally solved this without X-SendFile (which is probably the best practice). Anyway, for those who can't get X-Sendfile apache module to work (shared hosting), here's a solution:

// Generate response
$response = new Response();

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

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

$response->setContent(file_get_contents($filename));

return $response;

这篇关于Symfony2 - 强制下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆