Somfony 2 自动设置 header 内容 mime-types

Somfony 2 set header content mime-types automatically

我有一个关于 Symfony 2 的问题。 我想知道如何在 Symfony 2 中实现一个功能 return 内容 mime-type ?

为什么mime-type惹事?我有一些文件,我不希望每个人都可以访问它,然后我制作了一个方法来检查您是否有权访问此资源。

chdir("Directory/".$nameoftheressource);
$file = file_get_contents($nameoftheressource);/**/
$namearray=explode(".", $nameoftheressource);
$extension=end($namearray);

$returnFile= new Response();
$returnFile->setContent($file);
if($extension == "css" )
{ $returnFile->headers->set('Content-Type', 'text/css');
  return $returnFile;}

谢谢你,xabbuh,这接近完美地工作了,正如你所说,节省了很多时间 现在代码看起来像

编辑

    use Symfony\Component\HttpFoundation\BinaryFileResponse;
    //some code
    return new BinaryFileResponse('/Directory/'.$nameoftheressource);

但现在它确实显示 css 文件,但建议我下载它,但我想将其显示为 css 普通 css 文件

您可以使用 BinaryFileResponse class 节省大量代码,它会自动添加正确的内容类型 header。

您似乎想要提供受保护的 CSS 文件。在这种情况下,您可以使用以下代码并使用 Symfony 安全系统保护对此控制器的访问:

use Symfony\Component\HttpFoundation\BinaryFileResponse;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;

class DefaultController extends Controller
{
    /**
     * @Route("/css/app.css", name="css")
     * @Security("has_role('ROLE_ADMIN')")
     */
    public function renderCss()
    {
        $cssFilePath = $this->container->getParameter('kernel.root_dir').'/data/app.css';
        $cssContent = file_get_contents($cssFilePath);

        return Response($cssContent, 200, array('Content-Type' => 'text/css'));
    }
}