Symfony4.4:CSV 输出是不可能的

问题描述

我将应用程序从 Symfony 3.4 更新到 4.4 并验证了操作。
输出csv的功能不起作用,按下按钮后,页面重定向。
是通过下面链接的方法实现的,但是官方文档最多只有4.2。
是否有 4.2 或更高版本的替代方案?

https://symfony.com/doc/4.1/templating/formats.html

控制器

    /**
     * @Route("/",defaults={"_format"="html"},requirements={"_format"="html|csv"})
     * @Method("GET")
     *
     * @Template("@AppBundle/Hq/Post/index.html.twig")
     */
    public function indexAction(Request $request)
    {
        if ($request->getRequestFormat() == 'html') {
            // At the time of html output
        } elseif ($request->getRequestFormat() == 'csv') {
            // At the time of csv output
            // Set file name,no pagination
            $request->attributes->set('filename','post_article.csv');
        }

index.html.twig

    <button type="submit" class="btn" name="_format" value="csv">
        <i class="icon-download"></i> CSV output
    </button>

CsvListener

class CsvResponseListener
{
    /**
     * kernel.response Set the response at the time of CSV output in the event
     */
    public function onKernelResponse(FilterResponseEvent $event)
    {
        $request = $event->getRequest();
        $response = $event->getResponse();

        // Set the response at the time of CSV output in the event
        if ($request->getRequestFormat() === 'csv' && $response->getStatusCode() == 200) {
            // Convert response body to CRLF,SJIS-WIN
            $content = str_replace("\n","\r\n",$response->getContent());
            $content = mb_convert_encoding($content,'SJIS-WIN','UTF-8');
            $response->setContent($content);

            // Get the file name
            $filename = $request->attributes->get('filename','download.csv');

            // Set header for file download
            $response->headers->set('Content-Type','application/octet-stream');
            $response->headers->set('Content-Transfer-Encoding','binary');
            $response->headers->set('Content-Disposition','attachment; filename="'.$filename.'"');
            $response->headers->set('Content-Length',strlen(bin2hex($content)) / 2);
        }
    }
}

services.yaml

    app.listener.csvResponseListener:
        class: AppBundle\Listener\CsvResponseListener
        tags:
            - { name: kernel.event_listener,event: kernel.response,method: onKernelResponse }

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...