php - 将 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'))
抢占所有“你为什么这样做”的问题;我从远程服务获取这些图像。该服务的条款要求我在本地缓存图像。
解决方案
推荐阅读
- python - 通过 Python 下载 Smartsheet 附件
- reactjs - 将函数传递给上下文 API
- html - 如果浏览器同时支持这两个版本,哪些字体会被下载?
- php - Using Iterator and update_user_meta() to Dynamically Add Checkboxes to profile.php and edit-user.php in WordPress Using an Array
- c# - 使用 JWT 添加 [Authorize] 时无法访问页面
- google-cloud-sql - Prisma DATABASE_URL 错误(Cloud Run + Cloud SQL)
- java - 使用 localhost java 的 PayPal 测试 v2 api
- amazon-web-services - AWS - DSM 仅同步表并丢弃视图、序列、例程......等
- powershell - SASS 在 Azure Pipeline 中编译和保存
- php - 无法打开流:HTTP 请求失败!HTTP/1.1 400 错误请求 - PHP 错误