我有一个获取文件并将其返回给用户的Web服务(基于Symfony)。 自从我用curl做这个。
我刚发现guzzlehttp,看起来很棒。但是,我不知道如何使用guzzle执行此操作而不将下载的文件(xml或txt)保存到本地文件,从文件系统读取它并将其返回给用户。我想这样做而不保存到文件系统。
答案 0 :(得分:4)
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;
}
答案 1 :(得分:0)
$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());