symfony2 store uploaded file non rootweb

馋奶兔 提交于 2019-11-29 18:13:23

You could create a controller action to access files that are stored in a non public folder. In that action, you open file and stream in to browser.

See example at http://php.net/manual/en/function.readfile.php

You will need to change

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

to

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

UPDATE:

When you have your controller action that would stream requested file, you can render it in your TWIG by requesting that action with required file identifier:

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

Browser will treat streamed file the same way as if it was accessed directly, so you can apply any CSS to it.

UPDATE:

Sample controller action:

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

You could also use the "controller" function in twig:

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

will launch

the actionAction in ControllerController in AcmeBundle.

Hope this helps somehow.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!