简体   繁体   English

如何使用 guzzle 下载文件并将其转发到响应而不在本地保存

[英]How to download file using guzzle and forward it to response without saving locally

I'm using Laravel and I want to get files from api (with providing token and some headers) then forward it directly to the response without saving the file locally.我正在使用 Laravel 并且我想从 api 获取文件(提供令牌和一些标头),然后将其直接转发到响应而不在本地保存文件。

Currently I'm doing it like this:目前我正在这样做:

$response = $client->get($requestUrl, [
        'query' => [
            'hash' => $hash
        ],
        'headers' => [
            '_token_' => $oauthConfig['api_token'],
            '_token_issuer_' => 1
        ],
        'stream' => true,
    ]);

    $type = $response->getHeader('Content-Type')[0];
    $body = $response->getBody();

    $response = new StreamedResponse(function () use ($body) {
        while (!$body->eof()) {
            echo $body->read(1024);
        }
    });

    $response->headers->set('Content-Type', $type);

    return $response;

But I'm getting this exception:但我得到了这个例外:

LogicException
The content cannot be set on a StreamedResponse instance.

Any help / guidance is greatly appreciated.非常感谢任何帮助/指导。 Thanks.谢谢。

It seems the right thing to do is似乎正确的做法是

http://docs.guzzlephp.org/en/stable/psr7.html http://docs.guzzlephp.org/en/stable/psr7.html

use GuzzleHttp\Stream\Stream;



$response = $client->get($requestUrl, [
        'query' => [
            'hash' => $hash
        ],
        'headers' => [
            '_token_' => $oauthConfig['api_token'],
            '_token_issuer_' => 1
        ],
        'stream' => true,
    ]);

$result = '';
while(!$response->getBody()->eof()){
   $result .= $response->getBody()->read(8192);
}

$filename = 'test.gif';
return response()->streamDownload(function () use ($result) {
    echo $result;
}, $filename);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM