我有一个关于Symfony 2的问题,我想知道Symfony 2中是否有一个返回内容mime-type的函数?
为什么mime-type会引起麻烦? 我有一个文件,我不想让每个人都访问它,然后我做了一个methode,检查你是否有权利访问这个资源。
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文件。
你可以通过使用Symfony 2中的 BinaryFileResponse类 其中包括自动添加正确的内容类型头。
看来你想提供一个受保护的CSS文件,在这种情况下,你可以使用以下代码,并使用Symfony安全系统来保护对这个控制器的访问。在这种情况下,你可以使用下面的代码,并使用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'));
}
}