首页 > 解决方案 > Guzzle 6 下载文件

问题描述

需要帮助使用 Guzzle 6 从 REST API 下载文件。我不希望文件保存在本地,而是从网络浏览器下载。到目前为止的代码,但相信我遗漏了什么?

    <?php

//code for Guzzle etc removed

$responsesfile = $client->request('GET', 'documents/1234/content', 
        [
        'headers' => [
            'Cache-Control' => 'no-cache', 
            'Content-Type' => 'application/pdf',
            'Content-Type' => 'Content-Disposition: attachment; filename="test"'
        ]
        ]


    );
    return $responsesfile;
    ?>

标签: phpguzzleguzzle6

解决方案


只需在 Guzzle 的文档中进行研究,例如这里

传递一个字符串以指定将存储响应正文内容的文件的路径:

$client->request('GET', '/stream/20', ['sink' => '/path/to/file']);

传递从 fopen() 返回的资源以将响应写入 PHP 流:

$resource = fopen('/path/to/file', 'w');
$client->request('GET', '/stream/20', ['sink' => $resource]);

传递 Psr\Http\Message\StreamInterface 对象以将响应正文流式传输到打开的 PSR-7 流。

$resource = fopen('/path/to/file', 'w');
$stream = GuzzleHttp\Psr7\stream_for($resource);
$client->request('GET', '/stream/20', ['save_to' => $stream]);

推荐阅读