【问题标题】:Guzzle get file and forward itGuzzle 获取文件并转发
【发布时间】:2016-08-14 18:53:58
【问题描述】:

我有一个获取文件并将其返回给用户的网络服务(基于 Symfony)。 自从我使用 curl 来做到这一点。

我刚刚找到 guzzlehttp,它看起来很棒。但是,我不知道如何在不将下载的文件(xml 或 txt)保存到本地文件的情况下使用 guzzle 执行此操作,从文件系统中读取它并将其返回给用户。我想在不保存到文件系统的情况下执行此操作。

【问题讨论】:

    标签: symfony curl guzzle guzzle6


    【解决方案1】:
    $response = $client->request('GET', 'http://example.com/file', ['stream' => true]);
            $stream = $response->getBody();
            $content = new StreamedResponse(function () use ($stream) {
                /** @var StreamInterface $stream */
                while ($binary = $stream->read(1024)) {
                    echo $binary;
                    ob_flush();
                    flush();
                }
            }, $response->getStatusCode(), [
                'Content-Type' => $response->getHeaderLine('Content-Type'),
                'Content-Length' => $response->getHeaderLine('Content-Length'),
                'Content-Disposition' => $response->getHeaderLine('Content-Disposition')
            ]);
    
            return $this->renderResponse($content->send());
    

    【讨论】:

    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。 proper explanation 将通过展示为什么这是解决问题的好方法,并使其对有其他类似问题的未来读者更有用,从而大大提高其长期价值。请edit您的回答添加一些解释,包括您所做的假设。
    【解决方案2】:
    public function streamAction()
    {
         $response = $client->request(
            'GET', 'http://httpbin.org/stream-bytes/1024', ['stream' => true]
         );
    
         $body = $response->getBody();
    
         $response = new StreamedResponse(function() use ($body) {
             while (!$body->eof()) {
                 echo $body->read(1024);
             }
         });
    
         $response->headers->set('Content-Type', 'text/xml');
    
         return $response;
    }
    

    【讨论】:

    • 谢谢。完美运行。
    • 除此之外,您还可以使用sink option 将您的响应流式传输到STDOUT(PHP 的默认输出流的预定义常量)。
    猜你喜欢
    • 1970-01-01
    • 2013-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多