Symfony2:mime_content_type()未被识别

3

我的控制器看起来像这样:

public function download($filepath)
{
    // Generate response
    $response = new Response();

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

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

    $response->setContent(readfile($filepath));
}

将文件路径传递给它会导致以下错误消息:
Call to undefined function MyBundle\Controller\mime_content_type()

我该如何解决这个问题?
1个回答

0
尝试使用文件类
$oFile = new File($filepath);
$response->headers->set('Cache-Control', 'private');
$response->headers->set('Content-type', $oFile->getMimeType());
$response->headers->set('Content-Disposition', 'attachment; filepath="' . $oFile->getBasename() . '";');
$response->headers->set('Content-length', $oFile->getSize());

我还没有通过运行代码进行测试。希望这能正常工作。别忘了添加。

use Symfony\Component\HttpFoundation\File\File; 

在你的文件顶部放置语句。

希望这可以帮到你。


谢谢。我通过use添加了这个类,但是当我想通过$oFile = new File($filepath)创建一个文件实例时,PHPStorm告诉我这个类未定义。为什么?我忘了什么? - Max
@Max,请将您的语句与 use Symfony\Component\HttpFoundation\File\File; 匹配。我也已经更新了答案。 - jagad89
谢谢,这个方法可行。但是我收到了文件未找到的消息。以下是我在上面的代码中检索传递为参数的文件路径的方法:{% set filepath = asset('bundles/mybundle/files/example.pdf') %} <a href="{{ url('_route_bundle_download', { 'filepath': filepath|url_encode }) }}"> <button>Download</button> </a> 有什么问题吗? - Max
@Max 哦!!你正在传递URL。你有文件系统路径吗?如果有,那么将$filepath分配为系统路径。(例如C:/wamp/www/project/file.pdf) - jagad89

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接