Symfony:外部命令对浏览器的流式响应以显示命令的实时进度

问题描述

我正在symfony (4.2) framework生成一个包含2000页的大型PDF。我正在做的只是通过从树枝中获取内容来将HTML内容保存到.HTML文件中。

然后,我使用无头的chrome通过以下命令从URL生成PDF。

/usr/bin/google-chrome --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf [HTML文件的网址] --virtual-time-budget=10000

现在,要求是在运行以上命令时,我必须在前面显示进度条的加载程序。

我所做的如下操作以获取流响应并将其显示在浏览器中。

Controller

public function streamAction()
{
    $process = new Process(["pwd"]);
    $process->run();

    $output = new StreamedOutputService(fopen('PHP://stdout','w'));

    $response = new StreamedResponse(function() use ($output,$process) {
        // $process->isRunning() always returns false.
        while ($process->isRunning()) {
            $output->writeln($process->getoutput());
        }
    });
    $response->headers->set('X-Accel-Buffering','no');

    return $response;
}

Streamed Response Class

protected function doWrite($message,$newline)
{
    if (
        false === @fwrite($this->getStream(),$message) ||
        (
            $newline &&
            (false === @fwrite($this->getStream(),PHP_EOL))
        )
    ) {
        throw new RuntimeException('Unable to write output.');
    }

    echo $message;

    ob_flush();
    flush();
}

上述代码中的越野车是什么?我无法获取命令的输出,因此无法将其写入浏览器。

Below code is working fine and sending response at every 2 seconds on the browser

public function streamAction()
{
    $output = new StreamedOutputService(fopen('PHP://stdout','w'));

    $response = new StreamedResponse(function() use ($output) {
        for($i = 0; $i <= 5; $i++) {
             $output->writeln($i);
             sleep(2);
        }
    });
    $response->headers->set('X-Accel-Buffering','no');

    return $response;
}

谢谢。

解决方法

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

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

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