chaillouvincent
chaillouvincent

Reputation: 197

slim create response with guzzle streamFor content

I have an issue when building a slim (slim 4) response with a streamed content (a huge xlsx file content).

$fileHandler = \fopen(getenv('SHARED_FILES_PATH') . $filename, 'r');
if (!$fileHandler) {
    throw new \Exception('Unable to open file ' . getenv('SHARED_FILES_PATH') . $filename . ' for reading.');
}

$stream = GuzzleHttp\Psr7\Utils::streamFor($fileHandler);

// $this->response is Psr\Http\Message\ResponseInterface
$response = $this->response;
$response = $response->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
$response = $response->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response = $response->withBody($stream);

return $response;

The error: Fatal error: Uncaught RuntimeException: Unable to read from stream in /home/vincent/workspace/opco2i_applis/opco2i_portail/server/vendor/guzzlehttp/psr7/src/Stream.php on line 232

I have made some check and the file exists and is readable. If i do the following after the fopen call:

$contents = '';
while (!feof($fileHandler)) {
    $contents .= fread($fileHandler, 8192);
    break;
}
fclose($fileHandler);

var_dump($contents);die();

, i can read some content of my file.

Can you help me to find why guzzle stream cannot work in this case ?

Upvotes: 0

Views: 1520

Answers (1)

chaillouvincent
chaillouvincent

Reputation: 197

After some tests, i have found the solution. I must use $response->getBody()->write($stream) instead of $response->withBody($stream);

$stream = GuzzleHttp\Psr7\Utils::streamFor($fileHandler);

// $this->response is Psr\Http\Message\ResponseInterface
$response = $this->response;
$response = $response->withHeader('Content-Disposition', 'attachment; filename="' . $filename . '"');
$response = $response->withHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
$response = $response->getBody()->write($stream);

return $response;

Upvotes: 0

Related Questions