SF2自动设置头部内容mime-types

时间:2016-01-11 10:22:53

标签: symfony mime-types

我对Symfony 2有疑问。 我想知道如果在sf2中实现了一个返回内容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文件

2 个答案:

答案 0 :(得分:2)

您可以使用BinaryFileResponse class保存大量代码,其中包括自动添加正确的内容类型标题。

答案 1 :(得分:0)

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

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'));
    }
}