首页 > 解决方案 > 将 PSR-7 流写入文件

问题描述

我正在构建一个通读图像缓存,并且正在寻找一种将 PSR-7 流写入服务器上文件的方法。文档并不清楚如何执行此操作(它主要侧重于提供文件,而不是编写文件)。

我目前的最大努力使用$stream->detach()的并不理想(因为它破坏了基础流,然后我无法将其返回给用户)。有一个更好的方法吗?

/* @var GuzzleHttp\Client $httpClient */
$response = $httpClient->request(
  'GET', 'https://example.com/image.png'
);

// Validate response, etc.

$stream = $response->getBody();

$stream->isReadable(); // now true

$cachePath = '/path/to/local/cache/unique-name.png';

$writeHandle = fopen($cachePath, 'w');
stream_copy_to_stream($stream->detach(), $writeHandle);

$stream->isReadable(); // now false due to detach()

// To serve the data I'd need to create a new stream 
// from the image I've just created
return new GuzzleHttp\Psr7\Stream(fopen($cachePath, 'rb'))

抢占所有“你为什么这样做”的问题;我从远程服务获取这些图像。该服务的条款要求我在本地缓存图像。

标签: phpstreampsr-7

解决方案


推荐阅读