如何使用 Slim 在一个响应中发送数据流和字符串



我正在为更新工具构建一个Slim API。整个事情的目标是,经过一些检查,用一个Zip文件响应客户端。这工作得很好。 但我不仅想向客户端发送请求的zip文件,此外我还想添加一些从数据库中收集的信息。此信息是一个字符串。

现在我用zipfile响应的工作代码如下所示:

// up until this point several validations were successfully run, nothing special....
$zip = fopen($dir, 'r');
$response->write("$zip ");
$stream = new SlimHttpStream($zip); // create a stream instance for the response body
//$stream = new SlimHttpStream([$zip, $clientData]); // create a stream instance for the response body
//$response->getBody()->withStatus(200)->withBody("Hello, $name, ");
return $response->withHeader('Content-Type', 'application/force-download')
->withHeader('Content-Type', 'application/octet-stream')
->withHeader('Content-Type', 'application/download')
->withHeader('Content-Description', 'File Transfer')
->withHeader('Content-Transfer-Encoding', 'binary')
->withHeader('Expires', '0')
->withHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0')
->withHeader('key', $uuid)
->withBody($stream); // all stream contents will be sent to the response

我必须如何修改它以(在伪 php 中(执行此操作:

$zip = fopen($dir, 'r');
$response->write("$zip ");
$stream = new SlimHttpStream($zip); // create a stream instance for the response body
$queryResult = 'Some JSON as string';
$responseArray = [$stream, $queryResult];
return $response->withbody($responseArray);

我尝试了上述解决方案,但它无法正常工作。我收到 500 错误,但字符串仍然显示在网站上。我在这里错过了什么?

这不能直接在一个请求中完成。

您可以发送包含数据库详细信息的响应以及指向 JSON 有效负载中的 zip 文件的链接。

另一种方法是动态创建一个新的 zip 文件,其中包含一个包含数据库详细信息的文本文件和其中包含的原始 zip 文件。

作为另一种选择,如果您使用的是 HTTP/2,则可以发送数据库详细信息并通过Link标头使用服务器推送将 zip 文件推送到客户端。

最新更新