问题描述
我在使用流式内容(一个巨大的 xlsx 文件内容)构建纤薄(纤薄 4)响应时遇到问题。
$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;
错误: 致命错误:未捕获的运行时异常:无法从第 232 行的 /home/vincent/workspace/opco2i_applis/opco2i_portail/server/vendor/guzzlehttp/psr7/src/Stream.PHP 中的流读取
我做了一些检查,文件存在并且可读。 如果我在 fopen 调用后执行以下操作:
$contents = '';
while (!feof($fileHandler)) {
$contents .= fread($fileHandler,8192);
break;
}
fclose($fileHandler);
var_dump($contents);die();
你能帮我找出为什么在这种情况下狂饮流不能工作吗?
解决方法
经过一些测试,我找到了解决方案。 我必须使用 $response->getBody()->write($stream) 而不是 $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;