使用 guzzle streamFor 内容创建响应苗条

问题描述

我在使用流式内容一个巨大的 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;

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...