【问题标题】:How to download file using guzzle and forward it to response without saving locally如何使用 guzzle 下载文件并将其转发到响应而不在本地保存
【发布时间】:2020-12-01 23:15:15
【问题描述】:

我正在使用 Laravel,我想从 api 获取文件(提供令牌和一些标头),然后将其直接转发到响应而不在本地保存文件。

目前我正在这样做:

$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;

但我遇到了这个异常:

LogicException
The content cannot be set on a StreamedResponse instance.

非常感谢任何帮助/指导! 谢谢。

【问题讨论】:

    标签: php laravel api guzzle


    【解决方案1】:

    似乎正确的做法是

    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);
    

    【讨论】:

    • 调用未定义的方法 GuzzleHttp\Psr7\Response::eof()
    • 我得到的是 ����JFIF��C 而不是图像文件作为响应
    • 我仍然得到 ��JFIF��C !"$"$��C���"��������y��
    • 如何将其发送到响应以供下载? @Hackimov
    • 返回响应::download($result);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-16
    • 2021-11-07
    相关资源
    最近更新 更多