简体   繁体   中英

Using `sink` option in Guzzle to download a file resuls in empty file. Why that? And how to fix it?

I need to download a file using Guzzle. Currently I'm using version 6.3.3.

I pass the sink option to my request, but although the API I'm requesting responses a "200 OK" with some body content the destination file is always empty.

Here the code I have so far:

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

By the way, I'm calling this in the context of a Symfony (3.4) application in a command ( bin/console blah:custom-command ). The above code snippet is part of one of my service classes.

This results in a newly created but empty file and the following output in my terminal:

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

Does anybody have a clue what I am doing wrong? It's actually no rocket sciene. The more I'm confused now that the destination file for my download is created but its content won't be written…

Is there some kind of config missing for Guzzle or anything like that?

Dang it! It's absolutely my own fault. I should have posted the Guzzle Client's initialization as well. Then I could have identified my mistake slightly earlier…

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

Before I added the sink option (to download the response body as file) my service class had to handle the response line by line (because the API I'm working with responds with data of up to 1 GB size). Therefore I previsously added the stream option as well. This one is colliding with sink .

So, my solution is to simply remove the stream option from the Client's initialization. – Et voilà. It works.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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