的Symfony的公共目錄是your_project/web
,所以你不想有上傳私人文件。相反,您可以將它們上傳到特定的私人文件夾。下面
實例讓您上傳文件到your_project/Resources/private/uploads/images
文件夾,並在樹枝爲他們服務。當涉及到圖像服務時,它與傳統方式有點不同。你創建一條路線返回你的形象BinaryFileResponse
然後顯示在你的樹枝。
我在這裏張貼只是關鍵部分,但你可以看到完整的例子在這裏:Uploading images to a private directory and serving them in twig template
注意:您可以隨時更改的路怎麼以下工作路線。例如,name
參數可能是散列等。
服務器映像的控制器操作。 Twig稱之爲。
/**
* @param string $name
*
* @Method({"GET"})
* @Route("/{name}", name="image_show")
*
* @return Response
*/
public function showAction($name)
{
$response = new BinaryFileResponse($this->imageUploadPath.'/'.$name);
$response->trustXSendfileTypeHeader();
$response->setContentDisposition(
ResponseHeaderBag::DISPOSITION_INLINE,
$name,
iconv('UTF-8', 'ASCII//TRANSLIT', $name)
);
return $response;
}
這是顯示圖像的小枝部分。 images
變量來自indexAction()
,您可以在完整示例中看到。重要的部分是:{{ path('image_show', {'name': image}) }}
。它稱之爲上面的操作。
{% for image in images %}
<img src="{{ path('image_show', {'name': image}) }}" />
{% else %}
<em>No image found.</em>
{% endfor %}
謝謝您的回覆。我會試一試 – sheff2k1