我通過控制器爲受保護的圖像提供服務,以便在需要時從公共視圖中禁用其中的一些圖像。因此我使用BinaryFileResponse,實際上直接從Nginx提供圖像。
這裏是控制器:在symfony3中加載私人圖像需要太長的時間
location /images-internal/ {
internal;
alias /home/vagrant/Sites/Symfony/app/;
}
路線中的routing.yml:其中X-加速重定向啓用nginx的配置的
public function getPictureAction(Request $request, $id)
{
$image = $this->getDoctrine()
->getRepository('AppBundle:Images')
->getOneById($id);
$dir = $this->get('kernel')->getRootDir() . '/';
// Serving image by using Nginx's 'XSendfile'
$request->headers->set('X-Sendfile-Type', 'X-Accel-Redirect');
$request->headers->set('X-Accel-Mapping', $dir . '=/images-internal/');
BinaryFileResponse::trustXSendfileTypeHeader();
$path = $dir . 'images/image.jpg';
$response = new BinaryFileResponse($path);
$response->setContentDisposition(ResponseHeaderBag::DISPOSITION_INLINE);
return $response;
}
部分
picture_path:
path: /images/{id}
defaults: {_controller: AppBundle:Pages/Home:getPicture, _format: html}
methods: [GET]
options:
expose: true
在枝條模板我加載圖像是這樣的:
<img src="{{ path('picture_path', {'id': imageId}) }}">
使用此設置,53KB圖像的平均加載時間大約爲700ms。
出於測試目的,我用枝條的AssetExtension從公共Web目錄加載相同的圖像:
<img src="{{ asset('bundles/img/image.jpg') }}">
和負載時間正好是30毫秒!
這是正常的,它需要很長時間通過控制器來加載圖像,還是我做錯了什麼?
感謝您的回覆。我期待在Profiler中的性能,並看到Symfony防火牆需要大約500ms。所以看起來防火牆出現了問題。 – rvaliev