douxingmou4533 2019-04-01 09:56
浏览 100

将PSR-7流写入文件

I'm building a read-through image cache and I'm looking for a way to write PSR-7 streams to files on the server. The documentation isn't wonderfully clear on how to do this (it mostly focuses on serving files, rather than writing them).

My current best effort uses $stream->detach() which isn't ideal (as it destroys the underlying stream, which I then cannot return to the user). Is there a better way to do this?

/* @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'))

To preempt all the 'why are you doing this' questions; I'm getting these images from a remote service. The terms of that service requires me to cache images locally.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 目详情-五一模拟赛详情页
    • ¥15 有了解d3和topogram.js库的吗?有偿请教
    • ¥100 任意维数的K均值聚类
    • ¥15 stamps做sbas-insar,时序沉降图怎么画
    • ¥15 unity第一人称射击小游戏,有demo,在原脚本的基础上进行修改以达到要求
    • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
    • ¥15 关于#Java#的问题,如何解决?
    • ¥15 加热介质是液体,换热器壳侧导热系数和总的导热系数怎么算
    • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
    • ¥15 cmd cl 0x000007b