且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

symfony2 存储上传的文件非 rootweb

更新时间:2023-11-26 15:32:46

您可以创建控制器操作来访问存储在非公共文件夹中的文件.在该操作中,您打开文件并流式传输到浏览器.

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.

参见 http://php.net/manual/en/function.readfile 中的示例.php

你需要改变

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

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

更新:

当您拥有可以流式传输请求文件的控制器操作时,您可以通过使用所需的文件标识符请求该操作来在您的 TWIG 中呈现它:

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'}) }}">

浏览器会像对待直接访问一样对待流式文件,因此您可以对其应用任何 CSS.

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

更新:

示例控制器操作:

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