symfony2存储上传的文件非rootweb

时间:2013-09-18 19:34:04

标签: symfony upload twig x-sendfile

我上传文件有问题,我将上传的文件保存在非公共文件夹(非webroot文件夹)中,然后我想获取所有上传文件的webPAth,以便在视频库中使用它们。

$videos = $repository->getVideosThumbs($this->getUser());

然后在我的树枝上

{% for video in videos %}
         <a href ="{{ path('neoctus_videobundle_default_watchvideo', {'id' : video.id, 'salt' : app.user.salt }) }}" >
            <img id="{{ video.id }}" src="/uploads/images/{{video.imgPath}}" alt="1st image description" height="150" width="150"  />
         </a>
    {% endfor %}

但我无法访问图片,因为该文件夹不公开,我知道我必须通过x-sendFile,但我不知道如何在标题中发送多个jpeg文件,然后如何在树枝后恢复。

2 个答案:

答案 0 :(得分:1)

您可以创建控制器操作来访问存储在非公用文件夹中的文件。在该操作中,您打开文件并流入浏览器。

请参阅http://php.net/manual/en/function.readfile.php

上的示例

您需要更改

header('Content-Disposition: attachment; filename='.basename($file));

header('Content-Disposition: inline; filename='.basename($file));

<强>更新

如果您的控制器操作会流式传输所请求的文件,您可以通过请求具有所需文件标识符的操作在TWIG中呈现它:

<img src="{{ path('route_to_stream_action', {'fileId':'some_id'}) }}">

浏览器会像直接访问流式文件一样处理流式文件,因此您可以将任何CSS应用于它。

<强>更新

示例控制器操作:

public function streamFileAction($fileId)
{

    // implement your own logic to retrieve file using $fileId
    $file = $this->getFile($fileId);

    $filename = basename($file);

    $response = new StreamedResponse();
    $response->setCallback(function () use ($file){
        $handle = fopen($file->getRealPath(), 'rb');
        while (!feof($handle)) {
            $buffer = fread($handle, 1024);
            echo $buffer;
            flush();
        }
        fclose($handle);
    });
    $d = $response->headers->makeDisposition(ResponseHeaderBag::DISPOSITION_INLINE, $filename);
    $response->headers->set('Content-Disposition', $d);
    $response->headers->set('Content-Type', $file->getMimeType());

    return $response;
}

答案 1 :(得分:0)

你也可以使用&#34;控制器&#34;功能在树枝上:

{{ render(controller('AcmeBundle:Controller:action')) }}

将启动

AcmeBundle中ControllerController中的actionAction。

希望这会有所帮助。