【问题标题】:Using `sink` option in Guzzle to download a file resuls in empty file. Why that? And how to fix it?在 Guzzle 中使用 `sink` 选项下载文件会导致文件为空。为什么?以及如何解决?
【发布时间】:2019-04-15 09:15:18
【问题描述】:

我需要使用 Guzzle 下载文件。目前我使用的是 6.3.3 版本。

我将 sink 选项传递给我的请求,但尽管我请求的 API 响应带有一些正文内容的“200 OK”,但目标文件始终为空。

这是我到目前为止的代码:

// sidenote:
// $this->importFile is the absolute path to the file the contents have to be downloaded to
// $this->api is a GuzzleHttp\Client, base URL has been set previously
// $uri is the API endpoint's URI I am requesting (like "get/data")
// $this->getQueryParams() returns an array with a few needed parameters

$downloadDestination = fopen($this->importFile, 'w');

$response = $this->api->get($uri, [
    'query' => $this->getQueryParams(),
    'sink' => $downloadDestination,
]);

var_dump(file_get_contents($this->importFile));
var_dump($response->getBody()->getContents());
die;

顺便说一句,我在 Symfony (3.4) 应用程序的上下文中以命令 (bin/console blah:custom-command) 调用它。上面的代码 sn-p 是我的一个服务类的一部分。

这会在我的终端中生成一个新创建但为空的文件和以下输出:

string(0) ""
string(2065) "{"id":"123", … }"
# the latter one is actually a large JSON string, I just shortened it here

有人知道我做错了什么吗?这实际上不是火箭科学。我现在越是困惑,我下载的目标文件已经创建,但它的内容不会被写入......

Guzzle 是否缺少某种配置或类似的配置?

【问题讨论】:

    标签: php download guzzle guzzle6


    【解决方案1】:

    该死!这绝对是我自己的错。我也应该发布 Guzzle 客户端的初始化。那么我本可以更早地发现我的错误……

    $this->api = new Client([
        'base_uri' => $apiBaseUrl,
        'stream' => true,
    ]);
    

    在我添加 sink 选项(将响应主体下载为文件)之前,我的服务类必须逐行处理响应(因为我正在使用的 API 响应最大 1 GB 大小的数据) .因此,我之前也添加了 stream 选项。这个和sink发生冲突。

    所以,我的解决方案是简单地从客户端的初始化中删除stream 选项。 – 等等。它有效。

    【讨论】:

      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-04
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多